package orchestrator_test

import (
	"context"
	"path/filepath"
	"testing"
	"time"

	"github.com/flothus/tmux-xterm-research/server-go/internal/harness/event"
	"github.com/flothus/tmux-xterm-research/server-go/internal/harness/orchestrator"
	"github.com/flothus/tmux-xterm-research/server-go/internal/harness/store"
)

// TestNotificationsReadSurface is the V60 regression: user_notifications
// rows must be readable. Before the fix the table was write-only — the
// "Did I inform the user yet?" principle was broken at the surface layer.
func TestNotificationsReadSurface(t *testing.T) {
	tmp := t.TempDir()
	st, err := store.Open(filepath.Join(tmp, "harness.db"))
	if err != nil {
		t.Fatal(err)
	}
	defer st.Close()
	bus := event.NewBus(st)
	orch := orchestrator.New(st, bus)
	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancel()

	_ = orch.CreateRun(ctx, "run-notif", "notifications surface")

	now := store.FmtTime(store.Now())
	for i, kind := range []string{"completed", "unrouted", "clarification"} {
		_, _ = st.DB().Exec(`INSERT INTO user_notifications(run_id, task_id, kind, payload, created_at) VALUES('run-notif', NULL, ?, ?, ?)`,
			kind, "payload-"+kind, now)
		_ = i
	}
	// Add one for a different run that should NOT come back.
	_, _ = st.DB().Exec(`INSERT INTO user_notifications(run_id, task_id, kind, payload, created_at) VALUES('other-run', NULL, 'completed', 'other', ?)`, now)

	all, err := orch.ListNotifications(ctx, "run-notif", false)
	if err != nil {
		t.Fatal(err)
	}
	if len(all) != 3 {
		t.Errorf("ListNotifications returned %d, want 3 (got %+v)", len(all), all)
	}
	// Newest-first order.
	if len(all) >= 1 && all[0].Kind != "clarification" {
		t.Errorf("first notification kind = %s, want clarification (newest-first)", all[0].Kind)
	}

	// MarkDelivered + filter onlyPending.
	if err := orch.MarkNotificationDelivered(ctx, all[0].ID); err != nil {
		t.Fatalf("MarkNotificationDelivered: %v", err)
	}
	pending, err := orch.ListNotifications(ctx, "run-notif", true)
	if err != nil {
		t.Fatal(err)
	}
	if len(pending) != 2 {
		t.Errorf("pending after mark = %d, want 2", len(pending))
	}

	// Cross-run isolation.
	other, _ := orch.ListNotifications(ctx, "other-run", false)
	if len(other) != 1 {
		t.Errorf("other run returned %d notifications, want 1", len(other))
	}
}
