// Client Drizzle Postgres partage par l'app et Better Auth.
// Le throw est differe au premier usage runtime (Better Auth tape ici a la 1re
// requete) pour ne pas casser `next build` quand DATABASE_URL n'est pas disponible.

import { drizzle } from "drizzle-orm/postgres-js";
import postgres from "postgres";
import * as schema from "./schema";

declare global {
  // eslint-disable-next-line no-var
  var __novelia_pg__: ReturnType<typeof postgres> | undefined;
  // eslint-disable-next-line no-var
  var __novelia_db__: ReturnType<typeof drizzle<typeof schema>> | undefined;
}

function createClient() {
  const connectionString = process.env.DATABASE_URL;
  if (!connectionString) {
    throw new Error(
      "DATABASE_URL est manquante. Renseignez-la dans .env.local (dev) ou .env.production (prod)."
    );
  }
  return postgres(connectionString, {
    max: process.env.NODE_ENV === "production" ? 10 : 5,
    prepare: false,
  });
}

function getDb() {
  if (!globalThis.__novelia_db__) {
    const client = globalThis.__novelia_pg__ ?? createClient();
    globalThis.__novelia_pg__ = client;
    globalThis.__novelia_db__ = drizzle(client, { schema });
  }
  return globalThis.__novelia_db__;
}

// Proxy qui resout l'instance Drizzle a la 1re lecture de propriete.
// Permet d'importer `db` n'importe ou sans declencher la connexion a l'import.
export const db = new Proxy({} as ReturnType<typeof drizzle<typeof schema>>, {
  get(_target, prop) {
    const real = getDb() as unknown as Record<string | symbol, unknown>;
    const value = real[prop];
    return typeof value === "function" ? value.bind(real) : value;
  },
});

export type Database = ReturnType<typeof drizzle<typeof schema>>;
