import { MigrationInterface, QueryRunner } from "typeorm";

/**
 * Schedule-scoped wagon pins.
 *
 * Wagon occupancy now lives ONLY on each schedule's own train_set_wagons slots
 * (the per-schedule snapshot): pinning/releasing a wagon no longer mutates the
 * Wagon entity, so the same physical wagon can serve many schedules (the July 17
 * and July 20 runs of one train both use its 50 wagons). The Wagon columns
 * `current_train_schedule_id` / `train_set_wagon_id` keep only their physical
 * meaning — "out on this DISPATCHED train right now" (stamped at dispatch,
 * cleared at arrive/unload/cancel).
 *
 * This migration erases the legacy pin-time stamps left by the old flow: any
 * wagon pointing at a schedule that is not currently DISPATCHED (or that no
 * longer exists) gets its pointers cleared, and — when the old flow had parked
 * it in ASSIGNED — its status returns to the pool semantics (ASSIGNED only
 * while coupled to a built train, otherwise AVAILABLE).
 */
export class ScheduleScopedWagonPins2210000000000 implements MigrationInterface {
  name = "ScheduleScopedWagonPins2210000000000";

  public async up(queryRunner: QueryRunner): Promise<void> {
    await queryRunner.query(`
      UPDATE freight.wagons w
         SET current_train_schedule_id = NULL,
             train_set_wagon_id = NULL,
             status = CASE
               WHEN w.status = 'ASSIGNED' AND w.train_id IS NULL THEN 'AVAILABLE'
               ELSE w.status
             END
       WHERE w.deleted_at IS NULL
         AND w.current_train_schedule_id IS NOT NULL
         AND NOT EXISTS (
           SELECT 1
             FROM freight.train_schedules ts
            WHERE ts.id = w.current_train_schedule_id
              AND ts.deleted_at IS NULL
              AND ts.status = 'DISPATCHED'
         );
    `);
  }

  public async down(_queryRunner: QueryRunner): Promise<void> {
    // Pin-time stamps cannot be reconstructed (the data was the bug); the
    // slots on train_set_wagons still hold every live pin, so down is a no-op.
  }
}
