import { MigrationInterface, QueryRunner } from 'typeorm';

/**
 * Two-person wagon-transfer request queue. A requester records a count-only
 * request (N wagons of a type, from yard → to yard); OCC staff later pick the
 * physical wagons and execute the move. Replaces the single-step instant
 * bulk-transfer as the customer-facing yard-to-yard relocation path.
 */
export class CreateWagonTransferRequests2170000000000
  implements MigrationInterface
{
  name = 'CreateWagonTransferRequests2170000000000';

  public async up(queryRunner: QueryRunner): Promise<void> {
    await queryRunner.query(`
      CREATE TABLE IF NOT EXISTS freight.wagon_transfer_requests (
        id                    uuid        NOT NULL DEFAULT gen_random_uuid(),
        from_yard_id          uuid        NOT NULL,
        to_yard_id            uuid        NOT NULL,
        wagon_type_id         uuid        NOT NULL,
        quantity              integer     NOT NULL,
        status                varchar(20) NOT NULL DEFAULT 'PENDING',
        requested_by_user_id  uuid        NULL,
        fulfilled_by_user_id  uuid        NULL,
        fulfilled_at          timestamptz NULL,
        note                  text        NULL,
        created_at            timestamptz NOT NULL DEFAULT now(),
        updated_at            timestamptz NOT NULL DEFAULT now(),
        deleted_at            timestamptz NULL,
        CONSTRAINT pk_wagon_transfer_requests PRIMARY KEY (id),
        CONSTRAINT fk_wtr_from_yard    FOREIGN KEY (from_yard_id)  REFERENCES freight.yards (id),
        CONSTRAINT fk_wtr_to_yard      FOREIGN KEY (to_yard_id)    REFERENCES freight.yards (id),
        CONSTRAINT fk_wtr_wagon_type   FOREIGN KEY (wagon_type_id) REFERENCES freight.wagon_types (id),
        CONSTRAINT chk_wtr_quantity    CHECK (quantity > 0)
      )
    `);
    await queryRunner.query(`
      CREATE INDEX IF NOT EXISTS idx_wtr_status_from_yard
        ON freight.wagon_transfer_requests (status, from_yard_id)
    `);
  }

  public async down(queryRunner: QueryRunner): Promise<void> {
    await queryRunner.query(
      `DROP INDEX IF EXISTS freight.idx_wtr_status_from_yard`,
    );
    await queryRunner.query(
      `DROP TABLE IF EXISTS freight.wagon_transfer_requests`,
    );
  }
}
