// lib/prisma.ts
import { PrismaClient } from "@prisma/client";

// Prevent creating a new PrismaClient on every hot-reload in dev, which
// exhausts the Postgres connection pool.
const globalForPrisma = globalThis as unknown as {
  prisma: PrismaClient | undefined;
};

// Before the install wizard has run, DATABASE_URL may not exist yet.
// Passing datasourceUrl explicitly (instead of letting the client read
// env("DATABASE_URL") from schema.prisma) means construction never throws
// on a missing env var — Prisma only validates connectivity lazily, on the
// first actual query. Every route that touches this client is already
// gated behind the install check in middleware.ts, so pre-install this
// placeholder is simply never queried.
const databaseUrl =
  process.env.DATABASE_URL || "mysql://placeholder:placeholder@127.0.0.1:3306/placeholder";

export const prisma =
  globalForPrisma.prisma ??
  new PrismaClient({
    datasourceUrl: databaseUrl,
    log: process.env.NODE_ENV === "development" ? ["error", "warn"] : ["error"],
  });

if (process.env.NODE_ENV !== "production") {
  globalForPrisma.prisma = prisma;
}

export default prisma;
