import Database from "better-sqlite3";
import { mkdirSync } from "node:fs";
import { dirname, resolve } from "node:path";

export type AppDatabase = Database.Database;

function sqlitePathFromUrl(databaseUrl: string): string {
  if (databaseUrl.startsWith("sqlite:///")) {
    return databaseUrl.replace("sqlite://", "");
  }

  if (databaseUrl.startsWith("sqlite://")) {
    return databaseUrl.replace("sqlite://", "");
  }

  return databaseUrl;
}

export function openDatabase(databaseUrl = process.env.DATABASE_URL ?? "sqlite://./data/pi-chat.db"): AppDatabase {
  const filename = resolve(sqlitePathFromUrl(databaseUrl));
  mkdirSync(dirname(filename), { recursive: true });

  const db = new Database(filename);
  db.pragma("journal_mode = WAL");
  db.pragma("foreign_keys = ON");
  return db;
}
