import fs from "node:fs/promises";
import path from "node:path";
import sqlite3 from "sqlite3";
import { Database, open } from "sqlite";

export { Database };

export async function createDatabase(file: string): Promise<Database> {
  await fs.mkdir(path.dirname(file), { recursive: true });

  const db = await open({
    filename: file,
    driver: sqlite3.cached.Database,
  });

  const migrationsPath = new URL("./migrations", import.meta.url).pathname;
  await fs.chmod(file, 0o600);
  await db.migrate({ migrationsPath });

  return db;
}