package lidarrconfig

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

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

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

func newTestPool(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)
	// Reset singleton to default state before each test by replacing
	// the row contents via UPDATE (TRUNCATE would violate the CHECK).
	if _, err := pool.Exec(context.Background(),
		"UPDATE lidarr_config SET enabled=false, base_url=NULL, api_key=NULL, default_quality_profile_id=NULL, default_root_folder_path=NULL WHERE id=1",
	); err != nil {
		t.Fatalf("reset: %v", err)
	}
	return pool
}

func TestGet_DefaultRowReturnsZeroValueConfig(t *testing.T) {
	pool := newTestPool(t)
	cfg, err := New(pool).Get(context.Background())
	if err != nil {
		t.Fatalf("Get: %v", err)
	}
	if cfg.Enabled || cfg.BaseURL != "" || cfg.APIKey != "" {
		t.Errorf("expected zero-value Config, got %+v", cfg)
	}
}

func TestSaveThenGet_RoundTrip(t *testing.T) {
	pool := newTestPool(t)
	s := New(pool)
	want := Config{
		Enabled:                 true,
		BaseURL:                 "http://lidarr.lan:8686",
		APIKey:                  "secret",
		DefaultQualityProfileID: 4,
		DefaultRootFolderPath:   "/music",
	}
	if err := s.Save(context.Background(), want); err != nil {
		t.Fatalf("Save: %v", err)
	}
	got, err := s.Get(context.Background())
	if err != nil {
		t.Fatalf("Get: %v", err)
	}
	if got != want {
		t.Errorf("round-trip mismatch:\n got = %+v\nwant = %+v", got, want)
	}
}

func TestSave_EmptyValuesPersistAsNULL(t *testing.T) {
	pool := newTestPool(t)
	s := New(pool)
	if err := s.Save(context.Background(), Config{Enabled: false}); err != nil {
		t.Fatalf("Save: %v", err)
	}
	got, err := s.Get(context.Background())
	if err != nil {
		t.Fatalf("Get: %v", err)
	}
	if got.BaseURL != "" || got.APIKey != "" || got.DefaultRootFolderPath != "" {
		t.Errorf("expected empty strings on round-trip; got %+v", got)
	}
}
