import fs from 'node:fs';
import path from 'node:path';
import { DatabaseSync } from 'node:sqlite';
import { config } from './config.js';

export function openDatabase(filename = path.join(config.dataDir, 'wegwichtel.sqlite')) {
  const db = new DatabaseSync(filename, {
    enableForeignKeyConstraints: true,
    timeout: 5000
  });
  db.exec('PRAGMA journal_mode = WAL; PRAGMA busy_timeout = 5000;');
  const schema = fs.readFileSync(path.join(config.projectRoot, 'database', 'schema.sql'), 'utf8');
  db.exec(schema);
  return db;
}

export function transaction(db, callback) {
  db.exec('BEGIN IMMEDIATE');
  try {
    const result = callback();
    db.exec('COMMIT');
    return result;
  } catch (error) {
    db.exec('ROLLBACK');
    throw error;
  }
}
