import fs from "node:fs/promises";
import path from "node:path";
import { fileURLToPath } from "node:url";
import Database from "better-sqlite3";

// ── Paths ─────────────────────────────────────────────────────────────────────

const __dirname = path.dirname(fileURLToPath(import.meta.url));

const PATHS = {
  schema: path.join(__dirname, "schema.sql"),
  db: path.join(__dirname, "pipeline.db"),
};

// ── Init ──────────────────────────────────────────────────────────────────────

export async function initDb(): Promise<void> {
  const schema = await fs.readFile(PATHS.schema, "utf-8");
  const db = new Database(PATHS.db);

  db.pragma("journal_mode = WAL");
  db.pragma("foreign_keys = ON");
  db.exec(schema);
  db.close();

  console.log(`  pipeline.db initialised → ${PATHS.db}`);
}

// ── Main ─────────────────────────────────────────────────────────────────────

async function main(): Promise<void> {
  console.log("Initialising pipeline.db...");
  await initDb();
}

main().catch((err) => {
  console.error(err);
  process.exit(1);
});
