// src/db/index.ts
import 'dotenv/config';
import { relations } from './relations.ts';
import { drizzle } from "drizzle-orm/node-postgres";
import { Pool } from "pg";

const pool = new Pool({
  connectionString: process.env.DATABASE_URL,
  max: 10,
  idleTimeoutMillis: 30000,
  connectionTimeoutMillis: 2000,
});

// Handle pool errors to prevent connection corruption
pool.on('error', (err) => {
  console.error('Unexpected error on idle client', err);
});

export const db = drizzle({ client: pool, relations: relations, casing: 'snake_case' });
export type DBInstance = typeof db;

export const ClosePool = () => {
    pool.end();
}
