import { MigrationInterface, QueryRunner } from 'typeorm';

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

  public async up(queryRunner: QueryRunner): Promise<void> {
    await queryRunner.query(`
      ALTER TABLE freight.bookings
      ADD COLUMN IF NOT EXISTS selected_for_batch_at TIMESTAMPTZ NULL
    `);

    await queryRunner.query(`
      UPDATE freight.bookings
      SET
        status = 'SELECTED_FOR_BATCH',
        selected_for_batch_at = COALESCE(
          payment_deadline - INTERVAL '5 minutes',
          updated_at
        )
      WHERE status = 'AWAITING_PAYMENT'
    `);
  }

  public async down(queryRunner: QueryRunner): Promise<void> {
    await queryRunner.query(`
      UPDATE freight.bookings
      SET status = 'AWAITING_PAYMENT'
      WHERE status = 'SELECTED_FOR_BATCH'
    `);

    await queryRunner.query(`
      ALTER TABLE freight.bookings
      DROP COLUMN IF EXISTS selected_for_batch_at
    `);
  }
}
