package playsessions

import (
	"context"
	"io"
	"log/slog"
	"os"
	"testing"
	"time"

	"github.com/jackc/pgx/v5/pgtype"
	"github.com/jackc/pgx/v5/pgxpool"

	"git.fabledsword.com/bvandeusen/minstrel/internal/db"
	"git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq"
	"git.fabledsword.com/bvandeusen/minstrel/internal/dbtest"
)

func testPool(t *testing.T) *pgxpool.Pool {
	t.Helper()
	if testing.Short() {
		t.Skip("skipping integration test in -short mode")
	}
	dsn := os.Getenv("MINSTREL_TEST_DATABASE_URL")
	if dsn == "" {
		t.Skip("MINSTREL_TEST_DATABASE_URL not set")
	}
	if err := db.Migrate(dsn, slog.New(slog.NewTextHandler(io.Discard, nil))); err != nil {
		t.Fatalf("migrate: %v", err)
	}
	pool, err := pgxpool.New(context.Background(), dsn)
	if err != nil {
		t.Fatalf("pool: %v", err)
	}
	t.Cleanup(pool.Close)
	dbtest.ResetDB(t, pool)
	return pool
}

func seedTestUser(t *testing.T, pool *pgxpool.Pool) pgtype.UUID {
	t.Helper()
	u, err := dbq.New(pool).CreateUser(context.Background(), dbq.CreateUserParams{
		Username:     dbtest.TestUserPrefix + "tester",
		PasswordHash: "x",
		ApiToken:     "x",
		IsAdmin:      false,
	})
	if err != nil {
		t.Fatalf("CreateUser: %v", err)
	}
	return u.ID
}

func TestFindOrCreate_NoPriorSessionCreatesOne(t *testing.T) {
	pool := testPool(t)
	user := seedTestUser(t, pool)
	q := dbq.New(pool)

	now := time.Date(2026, 4, 25, 12, 0, 0, 0, time.UTC)
	id, err := FindOrCreate(context.Background(), q, user, now, "client-a", 30*time.Minute)
	if err != nil {
		t.Fatalf("FindOrCreate: %v", err)
	}
	if !id.Valid {
		t.Fatalf("session id not valid")
	}
	row, err := q.GetMostRecentPlaySessionForUser(context.Background(), user)
	if err != nil {
		t.Fatalf("get session: %v", err)
	}
	if row.ID != id {
		t.Errorf("returned id %v, db has %v", id, row.ID)
	}
	if !row.StartedAt.Time.Equal(now) {
		t.Errorf("started_at = %v, want %v", row.StartedAt.Time, now)
	}
}

func TestFindOrCreate_WithinWindowExtendsExisting(t *testing.T) {
	pool := testPool(t)
	user := seedTestUser(t, pool)
	q := dbq.New(pool)

	now := time.Date(2026, 4, 25, 12, 0, 0, 0, time.UTC)
	first, err := FindOrCreate(context.Background(), q, user, now, "client-a", 30*time.Minute)
	if err != nil {
		t.Fatalf("first: %v", err)
	}
	second, err := FindOrCreate(context.Background(), q, user, now.Add(15*time.Minute), "client-a", 30*time.Minute)
	if err != nil {
		t.Fatalf("second: %v", err)
	}
	if first != second {
		t.Errorf("session id changed: %v -> %v", first, second)
	}
	row, err := q.GetMostRecentPlaySessionForUser(context.Background(), user)
	if err != nil {
		t.Fatalf("get session: %v", err)
	}
	if !row.LastEventAt.Time.Equal(now.Add(15 * time.Minute)) {
		t.Errorf("last_event_at = %v", row.LastEventAt.Time)
	}
	if row.TrackCount != 2 {
		t.Errorf("track_count = %d, want 2", row.TrackCount)
	}
}

func TestFindOrCreate_BeyondWindowStartsNew(t *testing.T) {
	pool := testPool(t)
	user := seedTestUser(t, pool)
	q := dbq.New(pool)

	now := time.Date(2026, 4, 25, 12, 0, 0, 0, time.UTC)
	first, err := FindOrCreate(context.Background(), q, user, now, "client-a", 30*time.Minute)
	if err != nil {
		t.Fatalf("first: %v", err)
	}
	second, err := FindOrCreate(context.Background(), q, user, now.Add(31*time.Minute), "client-a", 30*time.Minute)
	if err != nil {
		t.Fatalf("second: %v", err)
	}
	if first == second {
		t.Errorf("expected new session, got same id %v", first)
	}
}

func TestFindOrCreate_AtExactBoundaryExtendsExisting(t *testing.T) {
	pool := testPool(t)
	user := seedTestUser(t, pool)
	q := dbq.New(pool)

	now := time.Date(2026, 4, 25, 12, 0, 0, 0, time.UTC)
	first, _ := FindOrCreate(context.Background(), q, user, now, "client-a", 30*time.Minute)
	second, err := FindOrCreate(context.Background(), q, user, now.Add(30*time.Minute), "client-a", 30*time.Minute)
	if err != nil {
		t.Fatalf("second: %v", err)
	}
	if first != second {
		t.Errorf("expected same session at exact boundary, got new id %v", second)
	}
}
