import { MigrationInterface, QueryRunner } from 'typeorm';

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

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

    await queryRunner.query(`
      UPDATE freight.bookings b
      SET freight_type = 'CONTAINER'
      WHERE EXISTS (
        SELECT 1 FROM freight.booking_container bc WHERE bc.booking_id = b.id
      );
    `);

    await queryRunner.query(`
      UPDATE freight.bookings b
      SET freight_type = 'BULK'
      WHERE freight_type IS NULL
        AND b.cargo_type_id IS NOT NULL
        AND EXISTS (
          SELECT 1 FROM freight.cargo_types ct
          WHERE ct.id = b.cargo_type_id AND ct.requires_director_approval = true
        );
    `);

    await queryRunner.query(`
      UPDATE freight.bookings
      SET freight_type = 'CONTAINER'
      WHERE freight_type IS NULL;
    `);

    await queryRunner.query(`
      ALTER TABLE freight.bookings
        ALTER COLUMN cargo_type_id DROP NOT NULL;
    `);

    await queryRunner.query(`
      ALTER TABLE freight.bookings
        ALTER COLUMN freight_type SET NOT NULL;
    `);

    await queryRunner.query(`
      ALTER TABLE freight.bookings
        ADD CONSTRAINT chk_bookings_freight_type
        CHECK (freight_type IN ('CONTAINER', 'BULK'));
    `);
  }

  public async down(queryRunner: QueryRunner): Promise<void> {
    await queryRunner.query(`
      ALTER TABLE freight.bookings DROP CONSTRAINT IF EXISTS chk_bookings_freight_type;
    `);
    await queryRunner.query(`
      ALTER TABLE freight.bookings DROP COLUMN IF EXISTS freight_type;
    `);
    await queryRunner.query(`
      UPDATE freight.bookings SET cargo_type_id = (
        SELECT id FROM freight.cargo_types LIMIT 1
      ) WHERE cargo_type_id IS NULL;
    `);
    await queryRunner.query(`
      ALTER TABLE freight.bookings
        ALTER COLUMN cargo_type_id SET NOT NULL;
    `);
  }
}
