import { PrismaClient } from "@prisma/client"
import { PrismaPg } from "@prisma/adapter-pg"
import { prismaQueryInsights } from "@prisma/sqlcommenter-query-insights"

const globalForPrisma = global as unknown as { prisma: PrismaClient }

const isProduction = process.env.NODE_ENV === "production"

const adapter = new PrismaPg({
  connectionString: process.env.DATABASE_URL ?? "",
})

export const prisma =
  globalForPrisma.prisma ||
  new PrismaClient({
    adapter,
    comments: [prismaQueryInsights()],
    log: isProduction
      ? [
          { emit: "event", level: "warn" },
          { emit: "event", level: "error" },
        ]
      : [
          { emit: "event", level: "query" },
          { emit: "event", level: "warn" },
          { emit: "event", level: "error" },
        ],
  })

if (!isProduction) globalForPrisma.prisma = prisma
