import { MigrationInterface, QueryRunner } from 'typeorm';

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

  public async up(queryRunner: QueryRunner): Promise<void> {
    await queryRunner.query(
      `ALTER TABLE freight.bookings ADD COLUMN IF NOT EXISTS booking_type VARCHAR(20) NOT NULL DEFAULT 'ONE_TIME';`,
    );
    await queryRunner.query(
      `ALTER TABLE freight.bookings ADD COLUMN IF NOT EXISTS expires_at TIMESTAMPTZ;`,
    );
    // General contracts have no shipment date at creation — relax the NOT NULL.
    await queryRunner.query(
      `ALTER TABLE freight.bookings ALTER COLUMN scheduled_date DROP NOT NULL;`,
    );
    await queryRunner.query(
      `CREATE INDEX IF NOT EXISTS idx_bookings_booking_type ON freight.bookings (booking_type);`,
    );
  }

  public async down(queryRunner: QueryRunner): Promise<void> {
    await queryRunner.query(
      `DROP INDEX IF EXISTS freight.idx_bookings_booking_type;`,
    );
    // Reinstate NOT NULL only if no null rows exist (general contracts would block it).
    await queryRunner.query(
      `ALTER TABLE freight.bookings ALTER COLUMN scheduled_date SET NOT NULL;`,
    );
    await queryRunner.query(
      `ALTER TABLE freight.bookings DROP COLUMN IF EXISTS expires_at;`,
    );
    await queryRunner.query(
      `ALTER TABLE freight.bookings DROP COLUMN IF EXISTS booking_type;`,
    );
  }
}
