export * from "./queries";
export * from "./seed";

import { drizzle } from "drizzle-orm/sqlite-proxy";
import { browser } from "$app/environment";

/**
 * Concrete client DB type (SQLocal-backed Drizzle via sqlite-proxy).
 * Exported to allow query helpers to accept the specific type without
 * creating circular type references.
 */
export type ClientDb = ReturnType<typeof drizzle>;

// this is kinda mid
export const sqlocal = browser ? await initDb() : null;
export const db = sqlocal ? drizzle(sqlocal.driver, sqlocal.batchDriver) : null;

async function initDb() {
	const { SQLocalDrizzle } = await import("sqlocal/drizzle");
	return new SQLocalDrizzle("database.sqlite3");
}

export function getClientDb() {
	if (!sqlocal || !db) throw "Client DB can only be accessed from the browser";
	return {
		db,
		overwriteDatabaseFile: sqlocal.overwriteDatabaseFile,
	};
}
