package main

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

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

func main() {
	// Load .env from backend root (cwd is backend/)
	if err := godotenv.Load(".env"); err != nil {
		log.Println("Warning: Error loading .env file, relying on system env")
	}

	host := os.Getenv("DB_HOST")
	if host == "" {
		// Fallback for debugging if env not picked up
		host = "localhost"
	}
	port := os.Getenv("DB_PORT")
	user := os.Getenv("DB_USER")
	password := os.Getenv("DB_PASSWORD")
	dbname := os.Getenv("DB_NAME")

	connStr := fmt.Sprintf("host=%s port=%s user=%s password=%s dbname=%s sslmode=disable",
		host, port, user, password, dbname)

	db, err := sql.Open("postgres", connStr)
	if err != nil {
		log.Fatal(err)
	}
	defer db.Close()

	if err := db.Ping(); err != nil {
		log.Fatal("Could not connect to DB:", err)
	}

	// Check for superadmin
	targetEmail := "superadmin" // This is what we put in email column
	var id, email, passHash string
	err = db.QueryRow("SELECT id, email, password_hash FROM core_users WHERE email = $1", targetEmail).Scan(&id, &email, &passHash)
	if err != nil {
		log.Fatalf("Error finding user '%s': %v", targetEmail, err)
	}

	fmt.Printf("User Found: ID=%s, Email=%s\n", id, email)
	fmt.Printf("Stored Hash: %s\n", passHash)

	// Verify Password
	// Verify Password
	targetPass := "Admin@2025!"
	valid, err := VerifyUserPassword(passHash, targetPass)
	if err != nil {
		fmt.Printf("❌ Password Verification Error: %v\n", err)
	} else if !valid {
		fmt.Printf("❌ Password Verification FAILED\n")
	} else {
		fmt.Printf("✅ Password Verification SUCCESS\n")
	}
}

func VerifyUserPassword(hash, password string) (bool, error) {
	err := bcrypt.CompareHashAndPassword([]byte(hash), []byte(password))
	if err != nil {
		if err == bcrypt.ErrMismatchedHashAndPassword {
			return false, nil
		}
		return false, err
	}
	return true, nil
}
