import "server-only";
import { drizzle } from "drizzle-orm/node-postgres";
import pg from "pg";
import * as schema from "@sidetrail/db";

const { Pool } = pg;

// Connection pool singleton
let pool: pg.Pool | null = null;

function getPool(): pg.Pool {
  if (!pool) {
    const connectionString = process.env.DATABASE_URL;
    if (!connectionString) {
      throw new Error("DATABASE_URL environment variable is required");
    }
    pool = new Pool({ connectionString });
  }
  return pool;
}

// Drizzle instance singleton
let drizzleInstance: ReturnType<typeof drizzle<typeof schema>> | null = null;

export function getDb() {
  if (!drizzleInstance) {
    drizzleInstance = drizzle(getPool(), { schema });
  }
  return drizzleInstance;
}

// Re-export schema for convenience
export * from "@sidetrail/db";
