/**
 * Shared SQLite utilities for all DB modules.
 * Eliminates duplicated init boilerplate (mkdirSync, WAL, busy_timeout).
 */

import { Database } from "bun:sqlite";
import { mkdirSync } from "fs";
import { dirname } from "path";

export interface OpenDbOptions {
  /** PRAGMA busy_timeout in ms. Default 500. */
  busyTimeout?: number;
  /** Enable foreign keys. Default false. */
  foreignKeys?: boolean;
  /** Open in readonly mode. Default false. */
  readonly?: boolean;
}

/**
 * Open (or create) a SQLite database with standard PRAGMA setup.
 * Ensures the parent directory exists, enables WAL mode, sets busy_timeout.
 */
export function openDb(dbPath: string, options: OpenDbOptions = {}): Database {
  const { busyTimeout = 500, foreignKeys = false, readonly = false } = options;

  if (dbPath !== ":memory:") {
    mkdirSync(dirname(dbPath), { recursive: true });
  }

  const db = readonly
    ? new Database(dbPath, { readonly: true })
    : new Database(dbPath);
  if (!readonly) {
    db.exec("PRAGMA journal_mode = WAL");
  }
  db.exec(`PRAGMA busy_timeout = ${busyTimeout}`);
  if (foreignKeys) {
    db.exec("PRAGMA foreign_keys = ON");
  }

  return db;
}

/**
 * Standard error message extraction.
 * Returns the error message string from an unknown caught value.
 */
export function errMsg(err: unknown): string {
  return err instanceof Error ? err.message : String(err);
}
