import { mkdirSync } from "node:fs";
import { dirname, resolve } from "node:path";
import { Database } from "bun:sqlite";
import { drizzle, type BunSQLiteDatabase } from "drizzle-orm/bun-sqlite";
import { dashboardDbSchema } from "./schema";
import { applyDashboardMigrations } from "./migrations";

export const DEFAULT_DATABASE_URL = "file:./data/dimensionlab.sqlite";

export type DashboardDatabase = BunSQLiteDatabase<typeof dashboardDbSchema> & {
  $client: Database;
};

export interface DashboardDatabaseConnection {
  db: DashboardDatabase;
  sqlite: Database;
  filename: string;
  close(): void;
}

export function openDashboardDatabase(
  databaseUrl = process.env.DATABASE_URL || DEFAULT_DATABASE_URL,
): DashboardDatabaseConnection {
  const filename = resolveSqliteFilename(databaseUrl);
  mkdirSync(dirname(filename), { recursive: true });

  const sqlite = new Database(filename, { create: true, readwrite: true });
  const db = drizzle(sqlite, { schema: dashboardDbSchema }) as DashboardDatabase;
  applyDashboardMigrations(db);

  return {
    db,
    sqlite,
    filename,
    close() {
      sqlite.close();
    },
  };
}

export function resolveSqliteFilename(databaseUrl: string): string {
  if (!databaseUrl.startsWith("file:")) {
    throw new Error(`Only file: SQLite DATABASE_URL values are supported: ${databaseUrl}`);
  }

  return resolve(databaseUrl.slice("file:".length));
}
