import { MigrationInterface, QueryRunner } from 'typeorm';

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

  public async up(queryRunner: QueryRunner): Promise<void> {
    await queryRunner.query(`
      CREATE TABLE IF NOT EXISTS freight.scheduling_events (
        id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
        train_schedule_id UUID NOT NULL,
        trigger VARCHAR(40) NOT NULL,
        actor_user_id UUID NULL,
        reason TEXT NULL,
        plan_snapshot JSONB NOT NULL DEFAULT '{}',
        displaced_booking_ids JSONB NOT NULL DEFAULT '[]',
        created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
        updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
        deleted_at TIMESTAMPTZ NULL
      )
    `);
    await queryRunner.query(`
      CREATE INDEX IF NOT EXISTS idx_scheduling_events_train_schedule_id
      ON freight.scheduling_events (train_schedule_id)
      WHERE deleted_at IS NULL
    `);
  }

  public async down(queryRunner: QueryRunner): Promise<void> {
    await queryRunner.query(`DROP INDEX IF EXISTS freight.idx_scheduling_events_train_schedule_id`);
    await queryRunner.query(`DROP TABLE IF EXISTS freight.scheduling_events`);
  }
}
