import { PrismaClient } from "@prisma/client"

declare global {
  var prisma: PrismaClient | undefined
}

// Resolve a robust DATABASE_URL for all runtimes (prod/dev)
const resolvedDatabaseUrl = (() => {
  const envUrl = process.env.DATABASE_URL?.trim()
  if (envUrl && envUrl.length > 0) return envUrl
  // Fallbacks by environment to ensure correctness in containers
  if (process.env.NODE_ENV === "production") {
    return "file:/app/data/db.sqlite"
  }
  return "file:./prisma/db.sqlite"
})()

export const prisma =
  global.prisma ?? new PrismaClient({ datasources: { db: { url: resolvedDatabaseUrl } } })

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