/**
 * 数据库连接池
 * 使用 pg (node-postgres) 连接复用现有 PostgreSQL
 */
import { Pool, PoolClient, QueryResult, QueryResultRow } from "pg";
import { DATABASE_URL } from "./env";

const pool = new Pool({
  connectionString: DATABASE_URL,
  max: 20,
  idleTimeoutMillis: 30000,
  connectionTimeoutMillis: 5000,
});

// 通用查询
export async function query<T extends QueryResultRow = Record<string, unknown>>(
  sql: string,
  params?: unknown[]
): Promise<QueryResult<T>> {
  const client = await pool.connect();
  try {
    return await client.query<T>(sql, params);
  } finally {
    client.release();
  }
}

// 事务
export async function transaction<T>(
  fn: (client: PoolClient) => Promise<T>
): Promise<T> {
  const client = await pool.connect();
  try {
    await client.query("BEGIN");
    const result = await fn(client);
    await client.query("COMMIT");
    return result;
  } catch (e) {
    await client.query("ROLLBACK");
    throw e;
  } finally {
    client.release();
  }
}

// 仅读查询（自动路由到只读副本，如果有的话）
export async function readQuery<T extends QueryResultRow = Record<string, unknown>>(
  sql: string,
  params?: unknown[]
): Promise<QueryResult<T>> {
  return query<T>(sql, params);
}

// 写入查询（使用主库）
export async function writeQuery<T extends QueryResultRow = Record<string, unknown>>(
  sql: string,
  params?: unknown[]
): Promise<QueryResult<T>> {
  return query<T>(sql, params);
}

// 关闭连接池
export async function closePool(): Promise<void> {
  await pool.end();
}

export { pool };

export async function getClient(): Promise<PoolClient> {
  return pool.connect();
}
