package db

import (
	"context"
	"embed"
	"log"

	"photum-backend/internal/config"
	"photum-backend/internal/db/generated"

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

//go:embed schema.sql
var schemaFS embed.FS

func Connect(cfg *config.Config) (*generated.Queries, *pgxpool.Pool) {
	log.Printf("Connecting to database with DSN: %#v", cfg.DBDsn)
	poolConfig, err := pgxpool.ParseConfig(cfg.DBDsn)
	if err != nil {
		log.Fatalf("Unable to parse DB DSN: %v", err)
	}

	// Diagnostic log (password presence only)
	if poolConfig != nil && poolConfig.ConnConfig != nil {
		hasPassword := poolConfig.ConnConfig.Password != ""
		log.Printf("DB config user=%s host=%s port=%d password_set=%t",
			poolConfig.ConnConfig.User,
			poolConfig.ConnConfig.Host,
			poolConfig.ConnConfig.Port,
			hasPassword,
		)
	}

	pool, err := pgxpool.NewWithConfig(context.Background(), poolConfig)
	if err != nil {
		log.Fatalf("Unable to connect to database: %v", err)
	}

	if err := pool.Ping(context.Background()); err != nil {
		log.Fatalf("Database ping failed: %v", err)
	}

	return generated.New(pool), pool
}

func Migrate(pool *pgxpool.Pool) {
	log.Println("Applying database migration...")
	schema, err := schemaFS.ReadFile("schema.sql")
	if err != nil {
		log.Fatalf("Failed to read schema file: %v", err)
	}

	if _, err := pool.Exec(context.Background(), string(schema)); err != nil {
		log.Fatalf("Failed to execute migration: %v", err)
	}
	log.Println("Database migration applied successfully.")
}
