import { PrismaClient } from '@prisma/client';
import { getServerConfig } from './serverConfig';

// PrismaClient is attached to the `global` object in development to prevent
// exhausting your database connection limit.

const getUrl = () => {
  const cfg = getServerConfig();
  const fromEnv = process.env.DATABASE_URL;
  const fallback = `mysql://${cfg.dbUser}:${cfg.dbPass}@${cfg.dbHost}:${cfg.dbPort}/${cfg.dbName}`;
  return fromEnv || fallback;
};

const prismaClientSingleton = () => {
  const url = getUrl();
  return new PrismaClient({ datasources: { db: { url } } });
};

type PrismaClientSingleton = ReturnType<typeof prismaClientSingleton>;

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

export const prisma = globalForPrisma.prisma ?? prismaClientSingleton();

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

export default prisma;

export const resetPrisma = () => {
  const url = getUrl();
  const client = new PrismaClient({ datasources: { db: { url } } });
  globalForPrisma.prisma = client;
  return client;
};
