package command

import (
	"context"
	"io"
	"strings"
	"testing"
	"time"

	"github.com/herbygillot/dockhand/internal/command/cmdtest"
	"github.com/herbygillot/dockhand/internal/term"
	"github.com/stretchr/testify/require"
)

// Regression: dispatch from the watch must preserve its invocation's
// selected tree/database/environment and injected host/dependencies.
func TestArchitectureWatchPreservesInvocation(t *testing.T) {
	cmdtest.CheckedBranch(t)
	cmdtest.Hosted(t).Timings.WatchPoll = 10 * time.Millisecond
	_, _, err := cmdtest.Dockhand(t, "check")
	require.NoError(t, err)

	ctx, cancel := context.WithTimeout(t.Context(), 30*time.Second)
	defer cancel()
	typed, typing := io.Pipe()
	defer typed.Close()
	defer typing.Close()
	var viewed cmdtest.SyncBuffer
	done := make(chan error, 1)
	go func() {
		done <- cmdtest.RunFor(t, ctx, []string{"status", "--watch"}, term.Streams{In: typed, Out: &viewed, Err: &viewed}.AsTerminal())
	}()
	require.Eventually(t, func() bool { return strings.Contains(viewed.String(), "dockhand status --watch · ") }, 20*time.Second, 10*time.Millisecond)
	_, err = io.WriteString(typing, "l\n")
	require.NoError(t, err)
	require.Eventually(t, func() bool { return strings.Contains(viewed.String(), "Press Enter to return to status.") }, 20*time.Second, 10*time.Millisecond)
	observed := viewed.String()
	_, err = io.WriteString(typing, "\nq\n")
	require.NoError(t, err)
	require.NoError(t, <-done)
	require.Contains(t, observed, "$ dockhand logs check-1\n")
	require.NotContains(t, observed, "dockhand:", "nested logs must run in the watch's valid fake tree/database, rather than process defaults")
}
