import { MigrationInterface, QueryRunner } from 'typeorm';

/**
 * Admin-managed catalog of IMPORT run numbers (even, Djibouti → Ethiopia)
 * selectable in the Train Builder. The paired EXPORT number is derived
 * (import − 1), so only the import side is configured. Seeded with the runs
 * historically hardcoded in the backoffice's trainRuns constants; admins add
 * new runs from the Dropdown Settings editor.
 */
export class SeedImportTrainNumbers2390000000000 implements MigrationInterface {
  name = 'SeedImportTrainNumbers2390000000000';
  private readonly code = 'import_train_numbers';
  private readonly options: string[] = [
    '8002',
    '8102',
    '8202',
    '8302',
    '8402',
    '8502',
    '8602',
    '8702',
    '8802',
    '8902',
    '9002',
  ];

  public async up(queryRunner: QueryRunner): Promise<void> {
    const existing = await queryRunner.query(
      `SELECT id FROM freight.dropdown_settings WHERE code = $1 LIMIT 1;`,
      [this.code],
    );
    if (existing.length > 0) return;

    const inserted = await queryRunner.query(
      `INSERT INTO freight.dropdown_settings (code, label, description, multiple, meta)
       VALUES ($1, $2, $3, false, $4::jsonb)
       RETURNING id;`,
      [
        this.code,
        'Import train numbers',
        'Even IMPORT run numbers (Djibouti → Ethiopia) selectable when building a train. The paired export number is derived automatically (import − 1).',
        JSON.stringify({ searchable: true, clearable: true }),
      ],
    );
    const settingId = inserted[0].id;

    for (let i = 0; i < this.options.length; i++) {
      const value = this.options[i];
      await queryRunner.query(
        `INSERT INTO freight.dropdown_options (setting_id, value, label, display_order)
         VALUES ($1, $2, $3, $4);`,
        [settingId, value, value, i],
      );
    }
  }

  public async down(queryRunner: QueryRunner): Promise<void> {
    await queryRunner.query(`DELETE FROM freight.dropdown_settings WHERE code = $1;`, [
      this.code,
    ]);
  }
}
