import postgres from 'postgres';
import { readFile } from 'node:fs/promises';
import { fileURLToPath } from 'node:url';
import { dirname, resolve } from 'node:path';
import type { Config } from './config.js';

const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);

export type Sql = ReturnType<typeof postgres>;

let sqlInstance: Sql | null = null;

export function getSql(config: Config): Sql {
  if (sqlInstance) return sqlInstance;
  sqlInstance = postgres(config.DATABASE_URL, {
    max: 10,
    idle_timeout: 30,
    connect_timeout: 10,
    onnotice: () => {},
  });
  return sqlInstance;
}

export async function applySchema(sql: Sql): Promise<void> {
  const schemaPath = resolve(__dirname, 'schema.sql');
  const ddl = await readFile(schemaPath, 'utf8');
  await sql.unsafe(ddl);
}

export async function pingDb(sql: Sql): Promise<boolean> {
  try {
    await sql`SELECT 1`;
    return true;
  } catch {
    return false;
  }
}

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