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

dotenv.config();

const connectionString = process.env.DATABASE_URL!;

if (!connectionString) {
  throw new Error('DATABASE_URL environment variable is required');
}

const useSsl =
  connectionString.includes('supabase.com') ||
  connectionString.includes('sslmode=require');

// prepare:false works better with Supabase transaction pooler + some drizzle setups
const client = postgres(connectionString, {
  prepare: false,
  ...(useSsl ? { ssl: 'require' as const } : {}),
});

export const db = drizzle(client);

export default db;
