package tests

import (
	"database/sql"
	"fmt"
	"os"
	"testing"

	_ "github.com/lib/pq"
	"golang.org/x/crypto/bcrypt"
)

// TestVerifyLogin is a DIAGNOSTIC test - it checks if the superadmin hash in the
// database matches the expected password+pepper. This test will SKIP (not fail)
// if the hash doesn't match, as it depends on database state.
//
// Run this test to debug login issues:
//
//	go test -v -run TestVerifyLogin ./tests/...
func TestVerifyLogin(t *testing.T) {
	// Skip in CI - this is a diagnostic/debugging tool only
	if os.Getenv("CI") != "" {
		t.Skip("Skipping database-dependent test in CI")
	}

	// Config
	dbURL := os.Getenv("DATABASE_URL")
	if dbURL == "" {
		dbURL = "postgres://yuki:xl1zfmr6e9bb@db-60059.dc-sp-1.absamcloud.com:26868/gohorsejobs_dev?sslmode=require"
	}
	// Updated to match deployed backend .env
	pepper := "some-random-string-for-password-hashing"
	password := "Admin@2025!"

	// Connect DB
	db, err := sql.Open("postgres", dbURL)
	if err != nil {
		t.Skipf("Skipping: Failed to connect to DB: %v", err)
	}
	defer db.Close()

	if err := db.Ping(); err != nil {
		t.Skipf("Skipping: Failed to ping DB: %v", err)
	}

	// Fetch User
	var hash string
	err = db.QueryRow("SELECT password_hash FROM users WHERE identifier = 'superadmin'").Scan(&hash)
	if err != nil {
		t.Skipf("Skipping: superadmin user not found: %v", err)
	}

	fmt.Printf("🔍 Found hash in DB: %s\n", hash)

	// Check expected hash (from migration 010)
	expectedHash := "$2a$10$x7AN/r8MpVylJnd2uq4HT.lZbbNCqHuBuadpsr4xV.KlsleITmR5."
	if hash != expectedHash {
		t.Logf("⚠️  Hash in DB doesn't match migration 010 hash")
		t.Logf("   Expected: %s", expectedHash)
		t.Logf("   Got:      %s", hash)
		t.Logf("   👉 Run: ./start.sh option 8 (Seed Reset LITE) to update")
	}

	// Verify
	passWithPepper := password + pepper
	err = bcrypt.CompareHashAndPassword([]byte(hash), []byte(passWithPepper))
	if err != nil {
		t.Logf("❌ Password verification failed with pepper '%s'", pepper)
		t.Logf("   This is expected if migrations haven't been re-run")
		t.Skip("Skipping: Hash doesn't match - run migrations to update")
	}

	t.Logf("✅ SUCCESS! Password verifies correctly with pepper '%s'", pepper)
}

// TestVerifyLoginNoPepper checks if hash was created without pepper (legacy)
func TestVerifyLoginNoPepper(t *testing.T) {
	// Skip in CI
	if os.Getenv("CI") != "" {
		t.Skip("Skipping database-dependent test in CI")
	}

	dbURL := os.Getenv("DATABASE_URL")
	if dbURL == "" {
		dbURL = "postgres://yuki:xl1zfmr6e9bb@db-60059.dc-sp-1.absamcloud.com:26868/gohorsejobs_dev?sslmode=require"
	}
	password := "Admin@2025!"

	db, err := sql.Open("postgres", dbURL)
	if err != nil {
		t.Skipf("Skipping: %v", err)
	}
	defer db.Close()

	var hash string
	err = db.QueryRow("SELECT password_hash FROM users WHERE identifier = 'superadmin'").Scan(&hash)
	if err != nil {
		t.Skipf("Skipping: superadmin not found: %v", err)
	}

	// Try WITHOUT pepper
	err = bcrypt.CompareHashAndPassword([]byte(hash), []byte(password))
	if err == nil {
		t.Log("⚠️  Hash matches password WITHOUT pepper - migration issue!")
	} else {
		t.Log("✅ Hash was NOT created without pepper (expected)")
	}
}
