// src/db/pg.ts
import { Pool } from "pg";

export type PgConfig = {
    connectionString?: string;     // e.g. postgres://user:pass@host:2432/cosmos_indexer_db
    host?: string;
    port?: number;
    user?: string;
    password?: string;
    database?: string;
    ssl?: boolean;
    applicationName?: string;
};

let pool: Pool | null = null;

export function createPgPool(cfg: PgConfig): Pool {
    if (pool) return pool;
    pool = new Pool({
        connectionString: cfg.connectionString,
        host: cfg.host,
        port: cfg.port,
        user: cfg.user,
        password: cfg.password,
        database: cfg.database,
        ssl: cfg.ssl ? { rejectUnauthorized: false } : undefined,
        application_name: cfg.applicationName ?? "cosmos-indexer",
        max: 10,             // tune if needed
        idleTimeoutMillis: 30_000,
    });
    return pool;
}

export function getPgPool(): Pool {
    if (!pool) throw new Error("PG pool is not initialized");
    return pool;
}

export async function closePgPool(): Promise<void> {
    if (pool) {
        await pool.end();
        pool = null;
    }
}