import { MigrationInterface, QueryRunner } from 'typeorm';

export class AddGrnNumberToWarehouseInventory1828000000000 implements MigrationInterface {
  name = 'AddGrnNumberToWarehouseInventory1828000000000';

  public async up(queryRunner: QueryRunner): Promise<void> {
    await queryRunner.query(`
      ALTER TABLE freight.warehouse_inventory
      ADD COLUMN IF NOT EXISTS grn_number VARCHAR(100) NULL
    `);

    await queryRunner.query(`
      UPDATE freight.warehouse_inventory
         SET grn_number = substring(notes FROM 'GRN Number: ([^\\n\\r]+)')
       WHERE grn_number IS NULL
         AND notes IS NOT NULL
         AND notes ~ 'GRN Number: '
    `);

    await queryRunner.query(`
      CREATE INDEX IF NOT EXISTS idx_warehouse_inventory_grn_number
      ON freight.warehouse_inventory(grn_number)
      WHERE grn_number IS NOT NULL
    `);
  }

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