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

// Rebreak Supabase Postgres – Prod: 5434 / Staging: 5435
const PROD_URL =
  "postgresql://postgres:iPva_XtETZMSJfTod1lt4Z8GYz4wkN7O@127.0.0.1:5434/postgres";
const STAGING_URL =
  "postgresql://postgres:iPva_XtETZMSJfTod1lt4Z8GYz4wkN7O@127.0.0.1:5435/postgres";

let _prisma: PrismaClient | null = null;

export function usePrisma(): PrismaClient {
  if (_prisma) return _prisma;

  const config = useRuntimeConfig();
  const isProduction = process.env.NODE_ENV === "production";
  const url =
    (config as any).databaseUrl || (isProduction ? PROD_URL : STAGING_URL);

  const adapter = new PrismaPg({ connectionString: url });
  _prisma = new PrismaClient({ adapter, log: ["error"] });
  return _prisma;
}
