import fs from 'fs';
import path from 'path';
import { DatabaseSync } from 'node:sqlite';
import { fileURLToPath } from 'url';
import dotenv from 'dotenv';

dotenv.config();

const __dirname = path.dirname(fileURLToPath(import.meta.url));
const sqlPath = path.join(__dirname, '..', 'database', 'init.sql');
const dbPath =
  process.env.SQLITE_PATH || path.join(__dirname, '..', 'data', 'crm.db');

fs.mkdirSync(path.dirname(dbPath), { recursive: true });

const sql = fs.readFileSync(sqlPath, 'utf8');

const db = new DatabaseSync(dbPath);
db.exec('PRAGMA foreign_keys = ON');

try {
  db.exec(sql);
  console.log('Datenbank-Schema ist bereit.');
} catch (e) {
  console.error(e);
  process.exit(1);
} finally {
  db.close();
}
