import { MigrationInterface, QueryRunner } from 'typeorm';

/**
 * Auto-load onto a selected train: a warehouse_loadings row now records WHICH
 * train the item was loaded onto (train_schedule_id), and wagon_id becomes
 * nullable because a schedule-level load may not resolve to a single wagon.
 */
export class WarehouseLoadingTrainAssociation2100000000000 implements MigrationInterface {
  name = 'WarehouseLoadingTrainAssociation2100000000000';

  public async up(queryRunner: QueryRunner): Promise<void> {
    await queryRunner.query(`
      ALTER TABLE freight.warehouse_loadings
        ADD COLUMN IF NOT EXISTS train_schedule_id UUID NULL
    `);
    await queryRunner.query(`
      ALTER TABLE freight.warehouse_loadings
        ALTER COLUMN wagon_id DROP NOT NULL
    `);
    await queryRunner.query(`
      CREATE INDEX IF NOT EXISTS idx_warehouse_loadings_train_schedule
        ON freight.warehouse_loadings(train_schedule_id)
        WHERE train_schedule_id IS NOT NULL
    `);
  }

  public async down(queryRunner: QueryRunner): Promise<void> {
    await queryRunner.query(`DROP INDEX IF EXISTS freight.idx_warehouse_loadings_train_schedule`);
    await queryRunner.query(`
      ALTER TABLE freight.warehouse_loadings DROP COLUMN IF EXISTS train_schedule_id
    `);
    // wagon_id stays nullable on revert: restoring NOT NULL would fail on rows
    // recorded without a wagon and re-introduce the outage this fixes.
  }
}
