package db

import (
    "context"
    "log"

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

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

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
}
