import { MigrationInterface, QueryRunner } from 'typeorm';

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

  public async up(queryRunner: QueryRunner): Promise<void> {
    await queryRunner.query(`
      ALTER TABLE freight.bookings
      ADD COLUMN IF NOT EXISTS is_government BOOLEAN NOT NULL DEFAULT false
    `);
    await queryRunner.query(`
      ALTER TABLE freight.bookings
      ADD COLUMN IF NOT EXISTS government_institution VARCHAR(255) NULL
    `);
    await queryRunner.query(`
      ALTER TABLE freight.bookings
      ALTER COLUMN company_id DROP NOT NULL
    `);
    await queryRunner.query(`
      CREATE INDEX IF NOT EXISTS idx_bookings_is_government
      ON freight.bookings (is_government)
      WHERE is_government = true AND deleted_at IS NULL
    `);
  }

  public async down(queryRunner: QueryRunner): Promise<void> {
    await queryRunner.query(`DROP INDEX IF EXISTS freight.idx_bookings_is_government`);
    await queryRunner.query(`
      UPDATE freight.bookings
      SET company_id = '00000000-0000-0000-0000-000000000000'
      WHERE company_id IS NULL
    `);
    await queryRunner.query(`
      ALTER TABLE freight.bookings
      ALTER COLUMN company_id SET NOT NULL
    `);
    await queryRunner.query(`
      ALTER TABLE freight.bookings
      DROP COLUMN IF EXISTS government_institution
    `);
    await queryRunner.query(`
      ALTER TABLE freight.bookings
      DROP COLUMN IF EXISTS is_government
    `);
  }
}
