package db

import (
	"fmt"
	"sync"
	"time"

	"github.com/jmoiron/sqlx"
	_ "github.com/lib/pq"
)

var (
	poolOnce sync.Once
	poolDB   *sqlx.DB
	poolErr  error
)

// OpenPool returns a process-wide *sqlx.DB. The first call connects; subsequent
// calls return the same instance. If the URL is empty, returns (nil, nil) — the
// caller is expected to handle the no-DB case (existing knowledge-platform
// endpoints work without a database; Akten/Deadline endpoints return 503).
//
// Pool sizing assumes a single Paliad replica behind Dokploy. Tune later if
// we scale horizontally.
func OpenPool(databaseURL string) (*sqlx.DB, error) {
	if databaseURL == "" {
		return nil, nil
	}
	poolOnce.Do(func() {
		conn, err := sqlx.Open("postgres", databaseURL)
		if err != nil {
			poolErr = fmt.Errorf("open pool: %w", err)
			return
		}
		conn.SetMaxOpenConns(10)
		conn.SetMaxIdleConns(5)
		conn.SetConnMaxLifetime(5 * time.Minute)

		if err := conn.Ping(); err != nil {
			poolErr = fmt.Errorf("ping pool: %w", err)
			return
		}
		poolDB = conn
	})
	return poolDB, poolErr
}
