/**
 * Dev helper: run the @tria-plc/iamapi-common TypeORM migrations against the shared `iam` schema.
 *
 * The package ships its migration CLI assuming you run it from inside the package repo (it needs
 * the package's devDeps). As a consumer we instead drive the shipped (compiled) migrations with the
 * passenger app's own installed TypeORM.
 *
 * Reads the same DATABASE_* env vars as the app's IAM DataSource (see config/iam-database.config.ts).
 * Run via:  pnpm --filter @edr/passenger-api iam:migrate
 * (the npm script loads .env with `node --env-file`).
 *
 * NOTE: in production the central IAM team owns/runs these migrations — this helper is for local dev.
 */
const path = require('path');
const { DataSource } = require('typeorm');

const iamDist = path
  .dirname(require.resolve('@tria-plc/iamapi-common'))
  .replace(/\\/g, '/');

const ds = new DataSource({
  type: 'postgres',
  host: process.env.DATABASE_HOST,
  port: Number(process.env.DATABASE_PORT || 5432),
  database: process.env.DATABASE_NAME,
  username: process.env.DATABASE_USER,
  password: process.env.DATABASE_PASSWORD,
  schema: process.env.DATABASE_SCHEMA || 'iam',
  entities: [], // migrations are raw SQL — no entities needed to run them
  migrations: [`${iamDist}/db/migrations/*.js`],
  migrationsTableName: 'typeorm_migrations',
});

(async () => {
  await ds.initialize();
  await ds.query('CREATE SCHEMA IF NOT EXISTS iam');
  // The IAM migrations rely on uuid_generate_v4() but never CREATE the extension themselves.
  await ds.query('CREATE EXTENSION IF NOT EXISTS "uuid-ossp"');
  const applied = await ds.runMigrations({ transaction: 'each' });
  console.log(`[iam-migrations] applied ${applied.length} migration(s)`);
  applied.slice(-5).forEach((m) => console.log('  +', m.name));
  await ds.destroy();
  console.log('[iam-migrations] DONE');
})().catch((e) => {
  console.error('[iam-migrations] FAIL:', e.message);
  process.exit(1);
});
