import { drizzle, type PostgresJsDatabase } from 'drizzle-orm/postgres-js';
import postgres from 'postgres';
import * as schema from './schema.js';
import { DEFAULT_DATABASE_URL } from './defaults.js';

export type Db = PostgresJsDatabase<typeof schema>;

export interface DbHandle {
  db: Db;
  close: () => Promise<void>;
}

export function createDb(url?: string): DbHandle {
  const connectionString = url ?? process.env['DATABASE_URL'] ?? DEFAULT_DATABASE_URL;
  const sql = postgres(connectionString, {
    // Pool sizing: allow up to 20 concurrent connections per gateway instance.
    // Each NestJS module (brain, preferences, memory, coord) shares this pool.
    max: Number(process.env['DB_POOL_MAX'] ?? 20),
    // Recycle idle connections after 30 s to avoid stale TCP state.
    idle_timeout: Number(process.env['DB_IDLE_TIMEOUT'] ?? 30),
    // Fail fast (5 s) on connection problems rather than hanging indefinitely.
    connect_timeout: Number(process.env['DB_CONNECT_TIMEOUT'] ?? 5),
  });
  const db = drizzle(sql, { schema });
  return { db, close: () => sql.end() };
}
