import { PrismaClient } from '@prisma/client';
import { PrismaPg } from '@prisma/adapter-pg';
import { Pool } from 'pg';

// 1. Setup the connection pool using your .env.local variable
const pool = new Pool({ connectionString: process.env.DATABASE_URL });
const adapter = new PrismaPg(pool);

// 2. Define the singleton logic
const prismaClientSingleton = () => {
  const client = new PrismaClient({ adapter });

  // ✅ HEALTH CHECK: Only runs once per client initialization
  client.$connect()
    .then(() => console.log("✅ Prisma 7 connected to PostgreSQL successfully"))
    .catch((err) => console.error("❌ Prisma connection error:", err));

  return client;
};

type PrismaClientSingleton = ReturnType<typeof prismaClientSingleton>;

const globalForPrisma = globalThis as unknown as {
  prisma: PrismaClientSingleton | undefined;
};

// 3. Export the client (reusing existing one if it exists)
export const prisma = globalForPrisma.prisma ?? prismaClientSingleton();

if (process.env.NODE_ENV !== 'production') globalForPrisma.prisma = prisma;

// BigInt fix for JSON serialization (needed for file sizes)
if (typeof BigInt !== 'undefined') {
  (BigInt.prototype as any).toJSON = function () {
    return Number(this);
  };
}