import NodeModule, { createRequire } from "module";
import fs from "fs";
import path from "path";
import type { PrismaClient as PrismaClientType } from "@prisma/client";

const req = createRequire(import.meta.url);

// Always ensure .env variables are loaded from disk
try {
  const envPath = path.resolve(process.cwd(), ".env");
  if (fs.existsSync(envPath)) {
    const envLines = fs.readFileSync(envPath, "utf-8").split("\n");
    for (const line of envLines) {
      const trimmed = line.trim();
      if (!trimmed || trimmed.startsWith("#")) continue;
      const eqIdx = trimmed.indexOf("=");
      if (eqIdx > 0) {
        const key = trimmed.substring(0, eqIdx).trim();
        let val = trimmed.substring(eqIdx + 1).trim();
        if ((val.startsWith('"') && val.endsWith('"')) || (val.startsWith("'") && val.endsWith("'"))) {
          val = val.substring(1, val.length - 1);
        }
        process.env[key] = val;
      }
    }
  }
} catch (e) {
  console.error("Failed to load .env in db.server.ts:", e);
}

// Clear Node module cache in development so schema additions are loaded dynamically
if (process.env.NODE_ENV !== "production") {
  const modCache = (NodeModule as any)._cache || (globalThis as any).require?.cache;
  if (modCache) {
    for (const key of Object.keys(modCache)) {
      if (key.includes(".prisma") || key.includes("@prisma")) {
        delete modCache[key];
      }
    }
  }
}

const { PrismaClient } = req("@prisma/client");

declare global {
  var prisma: PrismaClientType | undefined;
}

const dbUrl = process.env.DATABASE_URL;

const prisma: PrismaClientType =
  (globalThis as any).prisma ||
  global.prisma ||
  (dbUrl
    ? new PrismaClient({
        datasources: {
          db: {
            url: dbUrl,
          },
        },
      })
    : new PrismaClient());

(globalThis as any).prisma = prisma;
global.prisma = prisma;

export default prisma;


