// Top-level DB initializer for the Africa Alert PWA.
//
// After Track D (P1-9), the schema lives in Knex migration files under
// server/src/database/migrations/knex/ (one file per concern: core,
// academics, finance, hr, inventory, settings, misc). This script:
//   1. Runs all pending migrations via `knex.migrate.latest()`
//   2. Seeds the 4 demo accounts + the grading scales + a few lookup
//      rows via the seed files in server/src/database/seeds/.
//
// The original 151KB `db.exec(\`CREATE TABLE ...\`)` block has been
// replaced with a single ~50-line entrypoint. To regenerate the
// migration files from a fresh init.js dump, run
// `node tools/extract-migrations.js`.

const path = require('path');
const Database = require('better-sqlite3');
const { runMigrations } = require('./migrations/runner');
const { seedDemoData } = require('./seeds/demo');
const { seedGradingScales } = require('./seeds/grading_scales');

const DB_PATH = process.env.DB_PATH || path.join(__dirname, '..', '..', 'data', 'school.db');
console.log('[init] DB_PATH =', DB_PATH);

async function main() {
  // 1. Apply all pending migrations
  await runMigrations();

  // 2. Seed demo data + grading scales (idempotent)
  const db = new Database(DB_PATH);
  db.pragma('foreign_keys = ON');
  try {
    await seedDemoData(db);
    await seedGradingScales(db);
    const runPrimarySchoolSeed = require('./seed_dummy_data');
    runPrimarySchoolSeed(db);
  } finally {
    db.close();
  }

  console.log('[init] done');
}

main().catch(err => {
  console.error('[init] failed:', err);
  process.exit(1);
});
