import { MigrationInterface, QueryRunner } from 'typeorm';

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

  public async up(queryRunner: QueryRunner): Promise<void> {
    // Booking → target schedule (pool membership) + 1h pay-window deadline.
    await queryRunner.query(`
      ALTER TABLE freight.bookings
      ADD COLUMN IF NOT EXISTS train_schedule_id UUID NULL,
      ADD COLUMN IF NOT EXISTS payment_deadline TIMESTAMPTZ NULL
    `);
    await queryRunner.query(`
      CREATE INDEX IF NOT EXISTS idx_bookings_train_schedule_id
      ON freight.bookings (train_schedule_id)
      WHERE deleted_at IS NULL
    `);

    // TrainSchedule → booking-window status (OPEN/FULL/CLOSED).
    await queryRunner.query(`
      ALTER TABLE freight.train_schedules
      ADD COLUMN IF NOT EXISTS booking_window_status VARCHAR(10) NOT NULL DEFAULT 'OPEN'
    `);
    await queryRunner.query(`
      CREATE INDEX IF NOT EXISTS idx_train_schedules_booking_window_status
      ON freight.train_schedules (booking_window_status)
      WHERE deleted_at IS NULL
    `);
  }

  public async down(queryRunner: QueryRunner): Promise<void> {
    await queryRunner.query(
      `DROP INDEX IF EXISTS freight.idx_train_schedules_booking_window_status`,
    );
    await queryRunner.query(
      `ALTER TABLE freight.train_schedules DROP COLUMN IF EXISTS booking_window_status`,
    );
    await queryRunner.query(`DROP INDEX IF EXISTS freight.idx_bookings_train_schedule_id`);
    await queryRunner.query(`
      ALTER TABLE freight.bookings
      DROP COLUMN IF EXISTS train_schedule_id,
      DROP COLUMN IF EXISTS payment_deadline
    `);
  }
}
