package auth

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

	"github.com/jackc/pgx/v5/pgxpool"
	"golang.org/x/crypto/bcrypt"

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

// TestBootstrap_Integration exercises the admin-bootstrap flow against a real
// Postgres. Gated on MINSTREL_TEST_DATABASE_URL, skipped in -short mode.
func TestBootstrap_Integration(t *testing.T) {
	if testing.Short() {
		t.Skip("skipping bootstrap integration in -short mode")
	}
	dsn := os.Getenv("MINSTREL_TEST_DATABASE_URL")
	if dsn == "" {
		t.Skip("MINSTREL_TEST_DATABASE_URL not set; skipping")
	}
	ctx := context.Background()
	logger := slog.New(slog.NewTextHandler(io.Discard, nil))

	if err := db.Migrate(dsn, logger); err != nil {
		t.Fatalf("Migrate: %v", err)
	}

	pool, err := pgxpool.New(ctx, dsn)
	if err != nil {
		t.Fatalf("pool: %v", err)
	}
	t.Cleanup(pool.Close)

	// Bootstrap requires an empty users table to test the first-run path.
	// When the test DB is shared with the operator's dev environment, the
	// TRUNCATE wipes their real admin login. Save any non-test users now and
	// reinsert them after the test finishes so the operator can log back in.
	type savedUser struct {
		username, passwordHash, apiToken    string
		isAdmin, listenbrainzEnabled        bool
		subsonicPassword, listenbrainzToken *string
	}
	var saved []savedUser
	rows, err := pool.Query(ctx, `
		SELECT username, password_hash, api_token, is_admin,
		       subsonic_password, listenbrainz_token, listenbrainz_enabled
		  FROM users
		 WHERE username NOT LIKE 'test-%'`)
	if err != nil {
		t.Fatalf("save users: %v", err)
	}
	for rows.Next() {
		var s savedUser
		if err := rows.Scan(&s.username, &s.passwordHash, &s.apiToken, &s.isAdmin,
			&s.subsonicPassword, &s.listenbrainzToken, &s.listenbrainzEnabled); err != nil {
			rows.Close()
			t.Fatalf("scan: %v", err)
		}
		saved = append(saved, s)
	}
	rows.Close()
	t.Cleanup(func() {
		// Remove anything the test created, then restore non-test users.
		if _, err := pool.Exec(context.Background(), "TRUNCATE users RESTART IDENTITY CASCADE"); err != nil {
			t.Logf("cleanup truncate: %v", err)
			return
		}
		for _, s := range saved {
			if _, err := pool.Exec(context.Background(), `
				INSERT INTO users (username, password_hash, api_token, is_admin,
				                   subsonic_password, listenbrainz_token, listenbrainz_enabled)
				VALUES ($1, $2, $3, $4, $5, $6, $7)`,
				s.username, s.passwordHash, s.apiToken, s.isAdmin,
				s.subsonicPassword, s.listenbrainzToken, s.listenbrainzEnabled); err != nil {
				t.Logf("restore %q: %v", s.username, err)
			}
		}
	})

	if _, err := pool.Exec(ctx, "TRUNCATE users RESTART IDENTITY CASCADE"); err != nil {
		t.Fatalf("truncate: %v", err)
	}

	const testAdmin = "test-admin"
	cfg := config.AdminBootstrapConfig{Username: testAdmin, Password: "hunter2"}
	if err := Bootstrap(ctx, pool, cfg, logger); err != nil {
		t.Fatalf("Bootstrap: %v", err)
	}

	q := dbq.New(pool)
	user, err := q.GetUserByUsername(ctx, testAdmin)
	if err != nil {
		t.Fatalf("GetUserByUsername: %v", err)
	}
	if !user.IsAdmin {
		t.Error("bootstrapped user not marked admin")
	}
	if user.ApiToken == "" {
		t.Error("api_token empty")
	}
	if err := bcrypt.CompareHashAndPassword([]byte(user.PasswordHash), []byte("hunter2")); err != nil {
		t.Errorf("bcrypt compare: %v", err)
	}
	if user.SubsonicPassword == nil || *user.SubsonicPassword != "hunter2" {
		t.Errorf("subsonic_password = %v, want \"hunter2\"", user.SubsonicPassword)
	}

	byToken, err := q.GetUserByAPIToken(ctx, user.ApiToken)
	if err != nil {
		t.Fatalf("GetUserByAPIToken: %v", err)
	}
	if byToken.Username != testAdmin {
		t.Errorf("token lookup returned %q", byToken.Username)
	}

	// Second call must be a no-op because users table is non-empty.
	if err := Bootstrap(ctx, pool, cfg, logger); err != nil {
		t.Fatalf("Bootstrap (second call): %v", err)
	}
	count, err := q.CountUsers(ctx)
	if err != nil {
		t.Fatalf("CountUsers: %v", err)
	}
	if count != 1 {
		t.Errorf("expected exactly 1 user after idempotent bootstrap, got %d", count)
	}
}

// TestBootstrap_NoUsernameSkips verifies the no-config path without needing
// a database connection.
func TestBootstrap_NoUsernameSkips(t *testing.T) {
	err := Bootstrap(context.Background(), nil, config.AdminBootstrapConfig{}, slog.New(slog.NewTextHandler(io.Discard, nil)))
	if err != nil {
		t.Errorf("empty config should return nil, got %v", err)
	}
}
