import { PrismaClient } from "@prisma/client";
import { loadSystemConfig } from "./system-config";

let prisma: PrismaClient | null = null;

export async function getPrisma(): Promise<PrismaClient | null> {
  if (prisma) return prisma;

  const cfg = await loadSystemConfig();
  const url = cfg.db?.databaseUrl || process.env.DATABASE_URL;

  if (!url) return null;

  // Set env so Prisma picks it up at runtime
  process.env.DATABASE_URL = url;

  try {
    prisma = new PrismaClient();
    // quick connectivity check (non-fatal if it fails)
    await prisma.$queryRaw`SELECT 1`;
    return prisma;
  } catch {
    prisma = null;
    return null;
  }
}
