import { mkdirSync } from "node:fs";
import { dirname, join } from "node:path";

import Database from "better-sqlite3";

export function getAppDataDir() {
  return process.env.APP_DATA_DIR ?? "./data";
}

export function getDefaultDatabasePath() {
  return join(getAppDataDir(), "app.db");
}

export function createDatabase(dbPath = getDefaultDatabasePath()) {
  mkdirSync(dirname(dbPath), { recursive: true });
  const db = new Database(dbPath);
  db.pragma("journal_mode = WAL");
  db.pragma("foreign_keys = ON");
  return db;
}
