// Package database wraps pgx with a connection pool and transaction helpers.
package database

import (
	"context"
	"fmt"
	"strings"
	"time"

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

// New returns a pgx pool. The URL is required; no default is assumed so that a
// missing DATABASE_URL fails fast instead of pointing at an unintended DB.
func New(ctx context.Context, url string) (*pgxpool.Pool, error) {
	if url == "" {
		return nil, fmt.Errorf("database: DATABASE_URL is empty")
	}
	cfg, err := pgxpool.ParseConfig(url)
	if err != nil {
		return nil, fmt.Errorf("database: parse config: %w", err)
	}

	// Safe production connection pool defaults for resource-constrained VPS
	if !strings.Contains(url, "pool_max_conns") {
		cfg.MaxConns = 25
	}
	if !strings.Contains(url, "pool_min_conns") {
		cfg.MinConns = 2
	}
	if !strings.Contains(url, "pool_max_conn_lifetime") {
		cfg.MaxConnLifetime = 1 * time.Hour
	}
	if !strings.Contains(url, "pool_max_conn_idle_time") {
		cfg.MaxConnIdleTime = 15 * time.Minute
	}
	if !strings.Contains(url, "pool_health_check_period") {
		cfg.HealthCheckPeriod = 1 * time.Minute
	}

	pool, err := pgxpool.NewWithConfig(ctx, cfg)
	if err != nil {
		return nil, fmt.Errorf("database: create pool: %w", err)
	}
	pingCtx, cancel := context.WithTimeout(ctx, 5*time.Second)
	defer cancel()
	if err := pool.Ping(pingCtx); err != nil {
		pool.Close()
		return nil, fmt.Errorf("database: ping: %w", err)
	}
	return pool, nil
}

// Ping reports whether the pool can reach the database (used by /ready).
func Ping(ctx context.Context, pool *pgxpool.Pool) error {
	ctx, cancel := context.WithTimeout(ctx, 2*time.Second)
	defer cancel()
	return pool.Ping(ctx)
}
