// This is a server-only Drizzle client for Supabase Postgres via postgres-js.
import 'server-only';

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

const connectionString = process.env.DATABASE_URL;

if (!connectionString) {
  throw new Error('DATABASE_URL is not set in environment');
}

// Reuse a single client instance in dev to avoid exhausting connections.
const globalForDb = globalThis as unknown as {
  __drizzleSql?: ReturnType<typeof postgres>;
  __drizzleDb?: ReturnType<typeof drizzle>;
};

export const sql =
  globalForDb.__drizzleSql ??
  postgres(connectionString, {
    // Supabase often sits behind pgbouncer; these options are safe defaults.
    ssl: 'require',
    prepare: false,
  });

export const db = globalForDb.__drizzleDb ?? drizzle(sql);

if (process.env.NODE_ENV !== 'production') {
  globalForDb.__drizzleSql = sql;
  globalForDb.__drizzleDb = db;
}

export type DB = typeof db;

