import { MigrationInterface, QueryRunner } from 'typeorm';

/**
 * Train entity gained extended fields; baseline trains table only had code/capacity/status/notes.
 */
export class AddTrainExtendedColumns1750000000000 implements MigrationInterface {
  name = 'AddTrainExtendedColumns1750000000000';

  public async up(queryRunner: QueryRunner): Promise<void> {
    await queryRunner.query(`
      ALTER TABLE freight.trains
        ADD COLUMN IF NOT EXISTS train_number VARCHAR(20),
        ADD COLUMN IF NOT EXISTS train_name VARCHAR(100),
        ADD COLUMN IF NOT EXISTS route_id UUID,
        ADD COLUMN IF NOT EXISTS origin_station_id UUID,
        ADD COLUMN IF NOT EXISTS destination_station_id UUID,
        ADD COLUMN IF NOT EXISTS departure_time TIMESTAMPTZ,
        ADD COLUMN IF NOT EXISTS arrival_time TIMESTAMPTZ,
        ADD COLUMN IF NOT EXISTS locomotive_number VARCHAR(50),
        ADD COLUMN IF NOT EXISTS remarks TEXT;
    `);

    await queryRunner.query(`
      CREATE UNIQUE INDEX IF NOT EXISTS "UQ_trains_train_number"
        ON freight.trains (train_number)
        WHERE train_number IS NOT NULL;
    `);
  }

  public async down(queryRunner: QueryRunner): Promise<void> {
    await queryRunner.query(`DROP INDEX IF EXISTS freight."UQ_trains_train_number"`);
    await queryRunner.query(`
      ALTER TABLE freight.trains
        DROP COLUMN IF EXISTS remarks,
        DROP COLUMN IF EXISTS locomotive_number,
        DROP COLUMN IF EXISTS arrival_time,
        DROP COLUMN IF EXISTS departure_time,
        DROP COLUMN IF EXISTS destination_station_id,
        DROP COLUMN IF EXISTS origin_station_id,
        DROP COLUMN IF EXISTS route_id,
        DROP COLUMN IF EXISTS train_name,
        DROP COLUMN IF EXISTS train_number;
    `);
  }
}
