package team

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

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

func newSvc(t *testing.T) (*Service, string) {
	t.Helper()
	tmp := t.TempDir()
	st, err := store.Open(filepath.Join(tmp, "harness.db"))
	if err != nil {
		t.Fatalf("open: %v", err)
	}
	t.Cleanup(func() { st.Close() })
	return New(st), tmp
}

func TestCreateRespectsRosterCap(t *testing.T) {
	s, tmp := newSvc(t)
	bad := Team{ID: "t-x", Name: "x", MemoryPath: filepath.Join(tmp, "m.md"),
		Roster: []string{"a", "b", "c", "d", "e", "f"}}
	if err := s.Create(context.Background(), bad); err == nil {
		t.Errorf("expected roster cap error")
	}
}

func TestRecordOutcomeAndLoad(t *testing.T) {
	s, tmp := newSvc(t)
	mem := filepath.Join(tmp, "team-mem.md")
	tm := Team{ID: "tm1", Name: "frontend",
		Philosophy: "ship behind a flag",
		MemoryPath: mem,
		Roster:     []string{"lead", "a", "b"},
	}
	ctx := context.Background()
	if err := s.Create(ctx, tm); err != nil {
		t.Fatal(err)
	}
	if err := s.RecordOutcome(ctx, "tm1", "success", "add tooltip", "draft → review → impl", "shipped"); err != nil {
		t.Fatal(err)
	}
	if err := s.RecordOutcome(ctx, "tm1", "failure", "tooltip a11y", "skipped review", "regressed"); err != nil {
		t.Fatal(err)
	}
	body, err := s.LoadMemory(ctx, "tm1")
	if err != nil {
		t.Fatal(err)
	}
	if !strings.Contains(body, "kind: success") || !strings.Contains(body, "kind: failure") {
		t.Errorf("memory missing entries:\n%s", body)
	}
}

func TestSnapshotTemplate(t *testing.T) {
	s, tmp := newSvc(t)
	mem := filepath.Join(tmp, "team-mem.md")
	ctx := context.Background()
	_ = s.Create(ctx, Team{ID: "t1", Name: "x", MemoryPath: mem})
	_ = s.RecordOutcome(ctx, "t1", "success", "x", "y", "z")
	id, err := s.SnapshotTemplate(ctx, "t1", filepath.Join(tmp, "snapshots"))
	if err != nil {
		t.Fatal(err)
	}
	if id == "" {
		t.Fatal("empty template id")
	}
	// Verify the template file exists.
	var path string
	if err := s.St.DB().QueryRow(`SELECT snapshot_path FROM teams_templates WHERE id=?`, id).Scan(&path); err != nil {
		t.Fatal(err)
	}
	if _, err := s.St.DB().Exec(`SELECT 1 FROM teams_templates WHERE id=?`, id); err != nil {
		t.Fatal(err)
	}
}
