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

// Construire DATABASE_URL si elle n'est pas définie, en utilisant les variables individuelles
let databaseUrl = process.env.DATABASE_URL;

if (!databaseUrl) {
  const user = process.env.POSTGRES_USER || "gotgaming";
  const password = process.env.POSTGRES_PASSWORD || "change-this-in-production";
  const host = process.env.POSTGRES_HOST || "got-postgres";
  const port = process.env.POSTGRES_PORT || "5432";
  const db = process.env.POSTGRES_DB || "gotgaming";

  // Encoder le mot de passe pour l'URL
  const encodedPassword = encodeURIComponent(password);
  databaseUrl = `postgresql://${user}:${encodedPassword}@${host}:${port}/${db}?schema=public`;
}

if (typeof databaseUrl !== "string") {
  throw new Error("DATABASE_URL must be a string");
}

const pool = new Pool({
  connectionString: databaseUrl,
});

const adapter = new PrismaPg(pool);

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

export const prisma =
  globalForPrisma.prisma ??
  new PrismaClient({
    adapter,
    log: ["error"],
  });

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