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

import { env } from "@/lib/env";

import * as schema from "./schema";

/* Memoize across Next.js hot reloads so we don't exhaust the Postgres
   connection pool in dev. */
const globalForDb = globalThis as unknown as {
  __pg_client?: ReturnType<typeof postgres>;
};

const client =
  globalForDb.__pg_client ??
  postgres(env.DATABASE_URL, {
    max: 10,
  });

if (env.NODE_ENV !== "production") {
  globalForDb.__pg_client = client;
}

export const db = drizzle(client, { schema });
export type Db = typeof db;
