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

const globalForPrisma = globalThis as unknown as { prisma?: PrismaClient };

function hasExpectedDelegates(client: PrismaClient) {
  const prismaClient = client as unknown as {
    court?: { findMany?: unknown };
    sport?: { findMany?: unknown };
  };

  return (
    typeof prismaClient.court?.findMany === 'function' &&
    typeof prismaClient.sport?.findMany === 'function'
  );
}

function buildPrismaClient() {
  const databaseUrl = Bun.env.DATABASE_URL;

  if (!databaseUrl) {
    throw new Error('Missing DATABASE_URL in backend environment.');
  }

  const adapter = new PrismaPg({
    connectionString: databaseUrl,
  });

  return new PrismaClient({ adapter });
}

export function getPrismaClient() {
  if (globalForPrisma.prisma && hasExpectedDelegates(globalForPrisma.prisma)) {
    return globalForPrisma.prisma;
  }

  if (globalForPrisma.prisma && !hasExpectedDelegates(globalForPrisma.prisma)) {
    void globalForPrisma.prisma.$disconnect();
  }

  const prisma = buildPrismaClient();

  if (Bun.env.NODE_ENV !== 'production') {
    globalForPrisma.prisma = prisma;
  }

  return prisma;
}

export const db = getPrismaClient();
