import { MigrationInterface, QueryRunner } from 'typeorm';

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

  public async up(queryRunner: QueryRunner): Promise<void> {
    await queryRunner.query(`
      ALTER TABLE freight.train_schedules
      ADD COLUMN IF NOT EXISTS route_id UUID NULL;
    `);

    await queryRunner.query(`
      DO $$
      BEGIN
        IF NOT EXISTS (
          SELECT 1
          FROM pg_constraint
          WHERE conname = 'fk_train_schedules_route'
        ) THEN
          ALTER TABLE freight.train_schedules
          ADD CONSTRAINT fk_train_schedules_route
          FOREIGN KEY (route_id) REFERENCES freight.routes(id);
        END IF;
      END $$;
    `);

    await queryRunner.query(`
      CREATE INDEX IF NOT EXISTS idx_train_schedules_route_id
      ON freight.train_schedules(route_id);
    `);
  }

  public async down(queryRunner: QueryRunner): Promise<void> {
    await queryRunner.query(`DROP INDEX IF EXISTS freight.idx_train_schedules_route_id;`);
    await queryRunner.query(`
      ALTER TABLE freight.train_schedules
      DROP CONSTRAINT IF EXISTS fk_train_schedules_route;
    `);
    await queryRunner.query(`
      ALTER TABLE freight.train_schedules
      DROP COLUMN IF EXISTS route_id;
    `);
  }
}
