import { Database } from "bun:sqlite";
import { mkdirSync } from "node:fs";
import { dirname } from "node:path";
import { drizzle } from "drizzle-orm/bun-sqlite";
import { databasePath } from "./config";
import * as schema from "./schema";

mkdirSync(dirname(databasePath), { recursive: true });

export const sqlite = new Database(databasePath, { create: true, strict: true });
sqlite.exec("PRAGMA journal_mode = WAL;");
sqlite.exec("PRAGMA foreign_keys = ON;");
sqlite.exec("PRAGMA busy_timeout = 5000;");

export const db = drizzle(sqlite, { schema });

if (import.meta.hot) {
  import.meta.hot.dispose(() => sqlite.close());
}
