import { MigrationInterface, QueryRunner } from 'typeorm';

/**
 * Consist adjustments from a schedule: staff can trim free wagons off a built
 * train when their tare pushes gross weight over the locomotives' pull limit
 * (incl. overage tolerance), or couple extra yard wagons on while weight and
 * length headroom remain. Each add/remove is logged here so the schedule keeps
 * an auditable history; the built train itself is updated in place.
 *
 * Plain columns (no FKs) so the history survives wagon/train deletion.
 *
 * NOTE: the shared dev DB has no applied migration history, so this is also
 * hand-applied there. IF NOT EXISTS keeps that idempotent.
 */
export class ScheduleWagonAdjustmentLogs2170000000000 implements MigrationInterface {
  name = 'ScheduleWagonAdjustmentLogs2170000000000';

  public async up(queryRunner: QueryRunner): Promise<void> {
    await queryRunner.query(`
      CREATE TABLE IF NOT EXISTS freight.schedule_wagon_adjustment_logs (
        id uuid NOT NULL DEFAULT uuid_generate_v4(),
        train_schedule_id uuid NOT NULL,
        train_id uuid NOT NULL,
        action varchar(10) NOT NULL,
        wagon_id uuid NOT NULL,
        wagon_number varchar(50) NOT NULL,
        adjusted_by_user_id uuid,
        occurred_at timestamptz NOT NULL DEFAULT now(),
        created_at timestamptz NOT NULL DEFAULT now(),
        updated_at timestamptz NOT NULL DEFAULT now(),
        deleted_at timestamptz,
        CONSTRAINT "PK_schedule_wagon_adjustment_logs" PRIMARY KEY (id)
      );
    `);
    await queryRunner.query(`
      CREATE INDEX IF NOT EXISTS "IDX_swal_train_schedule_id"
        ON freight.schedule_wagon_adjustment_logs (train_schedule_id);
    `);
    await queryRunner.query(`
      CREATE INDEX IF NOT EXISTS "IDX_swal_train_id"
        ON freight.schedule_wagon_adjustment_logs (train_id);
    `);
  }

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