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

const connectionString = process.env.DATABASE_URL as string;
const writerConnectionString = process.env.WRITER_DATABASE_URL || connectionString;

// Definisikan tipe untuk global
declare global {
  var _postgresClient: postgres.Sql | undefined;
  var _postgresWriterClient: postgres.Sql | undefined;
}

// Gunakan koneksi global jika sudah ada, untuk mencegah PostgreSQL connection exhaustion di Next.js
const queryClient = global._postgresClient || postgres(connectionString, { max: 10 });
const queryWriterClient = global._postgresWriterClient || postgres(writerConnectionString, { max: 5 });

global._postgresClient = queryClient;
global._postgresWriterClient = queryWriterClient;

export const db = drizzle(queryClient, { schema });
export const writerDb = drizzle(queryWriterClient, { schema });
