import { drizzle as drizzlePg } from "drizzle-orm/node-postgres";
import { drizzle as drizzlePglite } from "drizzle-orm/pglite";
import type { NodePgDatabase } from "drizzle-orm/node-postgres";
import pg from "pg";
import { PGlite } from "@electric-sql/pglite";
import * as schema from "./schema.js";
import { env } from "../config/env.js";
import { ensureSchema } from "./init.js";

// Both drivers expose the same query API for our schema; we normalise the
// exported type to the node-postgres flavour to keep call sites simple.
export type AppDatabase = NodePgDatabase<typeof schema>;

let dbInstance: AppDatabase | null = null;

export async function initDb(): Promise<AppDatabase> {
  if (dbInstance) return dbInstance;

  if (env.databaseUrl) {
    const pool = new pg.Pool({ connectionString: env.databaseUrl });
    dbInstance = drizzlePg(pool, { schema });
    console.log("[db] using PostgreSQL (node-postgres)");
  } else {
    const client = new PGlite(env.pgliteDir);
    await client.waitReady;
    dbInstance = drizzlePglite(client, {
      schema,
    }) as unknown as AppDatabase;
    console.log(`[db] using embedded PGlite (${env.pgliteDir})`);
  }

  await ensureSchema(dbInstance);
  return dbInstance;
}

export function getDb(): AppDatabase {
  if (!dbInstance) {
    throw new Error("Database not initialised — call initDb() first");
  }
  return dbInstance;
}
