import { MigrationInterface, QueryRunner } from 'typeorm';

/**
 * Partial wagon-transfer fulfilment.
 *
 * A request for 50 wagons no longer has to be met in one go: OCC moves what the
 * source yard can spare, whenever it can, and the request stays open until the
 * full count is met (FULFILLED) or OCC ends it short (CLOSED_SHORT) so the
 * requester can ask another yard for the rest.
 *
 * Existing rows are back-filled so history keeps reading correctly: a FULFILLED
 * request delivered its whole quantity; anything else delivered nothing.
 */
export class AddWagonTransferPartialFulfilment2930000000000
  implements MigrationInterface
{
  public async up(queryRunner: QueryRunner): Promise<void> {
    await queryRunner.query(`
      ALTER TABLE freight.wagon_transfer_requests
        ADD COLUMN IF NOT EXISTS fulfilled_quantity integer NOT NULL DEFAULT 0,
        ADD COLUMN IF NOT EXISTS closed_short_at timestamptz NULL,
        ADD COLUMN IF NOT EXISTS closed_short_by_user_id uuid NULL
    `);
    await queryRunner.query(`
      UPDATE freight.wagon_transfer_requests
         SET fulfilled_quantity = quantity
       WHERE status = 'FULFILLED'
         AND fulfilled_quantity = 0
    `);
  }

  public async down(queryRunner: QueryRunner): Promise<void> {
    await queryRunner.query(`
      ALTER TABLE freight.wagon_transfer_requests
        DROP COLUMN IF EXISTS fulfilled_quantity,
        DROP COLUMN IF EXISTS closed_short_at,
        DROP COLUMN IF EXISTS closed_short_by_user_id
    `);
  }
}
