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

export * from './schema.js';
export { schema };
export { sql, eq, and, or, desc, asc, inArray, gte, lte, lt, gt, isNull, isNotNull, count } from 'drizzle-orm';

export type Database = PostgresJsDatabase<typeof schema>;

let cached: { client: postgres.Sql; db: Database } | null = null;

export function createDb(connectionString?: string): Database {
  if (cached) return cached.db;
  const url = connectionString ?? process.env.DATABASE_URL;
  if (!url) {
    throw new Error('DATABASE_URL not set');
  }
  const client = postgres(url, { max: 10, prepare: false });
  const db = drizzle(client, { schema });
  cached = { client, db };
  return db;
}

export async function closeDb(): Promise<void> {
  if (cached) {
    await cached.client.end({ timeout: 5 });
    cached = null;
  }
}
