import { MigrationInterface, QueryRunner } from 'typeorm';

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

  public async up(queryRunner: QueryRunner): Promise<void> {
    await queryRunner.query(`
      CREATE TABLE IF NOT EXISTS freight.train_checkpoint_events (
        id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
        train_schedule_id UUID NOT NULL REFERENCES freight.train_schedules(id) ON DELETE CASCADE,
        yard_id UUID NOT NULL,
        sequence_no INT NOT NULL,
        kind VARCHAR(20) NOT NULL,
        occurred_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
        note TEXT NULL,
        recorded_by_user_id UUID NULL,
        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_train_checkpoint_events_schedule
      ON freight.train_checkpoint_events (train_schedule_id, sequence_no)
      WHERE deleted_at IS NULL
    `);
  }

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