#!/usr/bin/env node
// Build data/avtoambor.db from schema.sql + seed.sql.
// Safe to run from anywhere — paths are resolved relative to this file.

import Database from 'better-sqlite3';
import { readFileSync, mkdirSync, existsSync } from 'node:fs';
import { fileURLToPath } from 'node:url';
import { dirname, resolve } from 'node:path';

const __dirname = dirname(fileURLToPath(import.meta.url));
const ROOT      = resolve(__dirname, '..');
const DATA_DIR  = resolve(ROOT, 'data');
const DB_PATH   = resolve(DATA_DIR, 'avtoambor.db');
const SCHEMA    = resolve(ROOT, 'src/lib/server/schema.sql');
const SEED      = resolve(ROOT, 'src/lib/server/seed.sql');

if (!existsSync(DATA_DIR)) mkdirSync(DATA_DIR, { recursive: true });

const db = new Database(DB_PATH);
db.pragma('journal_mode = WAL');
db.pragma('foreign_keys = ON');

console.log(`[init-db] applying schema → ${DB_PATH}`);
db.exec(readFileSync(SCHEMA, 'utf8'));

const partsCount = db.prepare(`SELECT COUNT(*) AS n FROM parts`).get().n;
if (partsCount === 0) {
  console.log('[init-db] inserting seed data…');
  db.exec(readFileSync(SEED, 'utf8'));
} else {
  console.log(`[init-db] parts table already has ${partsCount} rows — skipping seed.`);
}

db.close();
console.log('[init-db] done.');
