import { MigrationInterface, QueryRunner } from 'typeorm';

/**
 * Every built train owns a fixed pair of run numbers, typed at build time:
 * an EXPORT number (odd, e.g. 8001) and an IMPORT number (even, e.g. 8002).
 * Scheduling copies the route-direction-matched number onto the schedule at
 * creation; legacy trains with a null pair keep dispatch-time pool assignment.
 *
 * NOTE: the shared dev DB has no applied migration history, so this is also
 * hand-applied there. IF NOT EXISTS keeps that idempotent.
 */
export class TrainNumberPair2200000000000 implements MigrationInterface {
  name = 'TrainNumberPair2200000000000';

  public async up(queryRunner: QueryRunner): Promise<void> {
    await queryRunner.query(`
      ALTER TABLE freight.trains
        ADD COLUMN IF NOT EXISTS import_train_number varchar(20),
        ADD COLUMN IF NOT EXISTS export_train_number varchar(20);
    `);
    await queryRunner.query(`
      CREATE UNIQUE INDEX IF NOT EXISTS "UQ_trains_import_train_number"
        ON freight.trains (import_train_number)
        WHERE import_train_number IS NOT NULL;
    `);
    await queryRunner.query(`
      CREATE UNIQUE INDEX IF NOT EXISTS "UQ_trains_export_train_number"
        ON freight.trains (export_train_number)
        WHERE export_train_number IS NOT NULL;
    `);
  }

  public async down(queryRunner: QueryRunner): Promise<void> {
    await queryRunner.query(`DROP INDEX IF EXISTS freight."UQ_trains_export_train_number";`);
    await queryRunner.query(`DROP INDEX IF EXISTS freight."UQ_trains_import_train_number";`);
    await queryRunner.query(`
      ALTER TABLE freight.trains
        DROP COLUMN IF EXISTS export_train_number,
        DROP COLUMN IF EXISTS import_train_number;
    `);
  }
}
