import { MigrationInterface, QueryRunner } from "typeorm";

/**
 * Add a frozen wagon-allocation snapshot to each train schedule.
 *
 * Once a schedule leaves the editable DRAFT/SCHEDULED phase (dispatch / arrive /
 * cancel), the same physical wagons get released and re-pinned onto later trains.
 * The live wagon↔slot joins then no longer describe THIS train's plan, so an
 * admin viewing a past schedule saw a mangled or "unavailable" allocation.
 *
 * This jsonb column stores a one-shot frozen copy of the wagon plan (per-slot
 * physical wagon + booking allocations) captured at the transition. Non-editable
 * schedules render from the snapshot; DRAFT/SCHEDULED still read live. NULL on
 * legacy rows and while editable — the read path falls back to the live joins.
 */
export class AddScheduleWagonAllocationSnapshot2120000000000
  implements MigrationInterface
{
  name = "AddScheduleWagonAllocationSnapshot2120000000000";

  public async up(queryRunner: QueryRunner): Promise<void> {
    await queryRunner.query(`
      ALTER TABLE freight.train_schedules
        ADD COLUMN IF NOT EXISTS wagon_allocation_snapshot jsonb;
    `);
  }

  public async down(queryRunner: QueryRunner): Promise<void> {
    await queryRunner.query(`
      ALTER TABLE freight.train_schedules
        DROP COLUMN IF EXISTS wagon_allocation_snapshot;
    `);
  }
}
