import { MigrationInterface, QueryRunner, TableColumn } from 'typeorm';

/**
 * Catch-up for environments where AddWarehouseInspection ran before the
 * warehouse module table existed. Production needs this column for unload and
 * inspection flows because the WarehouseInventory entity maps inspectionStatus.
 */
export class EnsureWarehouseInventoryInspectionStatus1821000000001 implements MigrationInterface {
  private readonly table = 'freight.warehouse_inventory';

  public async up(queryRunner: QueryRunner): Promise<void> {
    if (!(await queryRunner.hasColumn(this.table, 'inspection_status'))) {
      await queryRunner.addColumn(
        this.table,
        new TableColumn({
          name: 'inspection_status',
          type: 'varchar',
          length: '20',
          isNullable: true,
        }),
      );
    }

    await queryRunner.query(`
      CREATE INDEX IF NOT EXISTS idx_warehouse_inventory_inspection_status
      ON freight.warehouse_inventory(inspection_status)
    `);
  }

  public async down(queryRunner: QueryRunner): Promise<void> {
    await queryRunner.query(`
      DROP INDEX IF EXISTS freight.idx_warehouse_inventory_inspection_status
    `);

    if (await queryRunner.hasColumn(this.table, 'inspection_status')) {
      await queryRunner.dropColumn(this.table, 'inspection_status');
    }
  }
}
