import { MigrationInterface, QueryRunner } from "typeorm";

/**
 * Add a global "booking close offset" — how long BEFORE departure a schedule's
 * booking window shuts — configurable separately for import and export.
 *
 * When an offset is set, the window's close instant is `departure − offset`
 * (e.g. departure 17:00 with a 3-hour import offset closes at 14:00; departure
 * Jul-10 16:00 with a 1-day export offset closes Jul-9 16:00). It caps the whole
 * booking lifecycle: the first window close, every reopen cycle, and the export
 * FCFS close all land at/at-or-before this cutoff instead of at departure.
 *
 * NULL / 0 preserves the previous behaviour exactly (import closes at
 * open+duration clamped to departure; export closes at departure), so existing
 * installs are unaffected until an offset is entered.
 *
 * `*_close_offset_minutes` on the global-rules singleton is the live config; the
 * matching `rule_*_close_offset_minutes` snapshot on each schedule freezes it at
 * creation so the batch board keeps drawing the window the customer was shown
 * even after a later global-rules edit. Both are nullable with no backfill —
 * absent means "no offset", the safe default.
 */
export class AddBookingCloseOffset2330000000000 implements MigrationInterface {
  name = "AddBookingCloseOffset2330000000000";

  public async up(queryRunner: QueryRunner): Promise<void> {
    await queryRunner.query(`
      ALTER TABLE freight.train_scheduling_global_rules
        ADD COLUMN IF NOT EXISTS import_close_offset_minutes integer,
        ADD COLUMN IF NOT EXISTS export_close_offset_minutes integer;
    `);

    await queryRunner.query(`
      ALTER TABLE freight.train_schedules
        ADD COLUMN IF NOT EXISTS rule_import_close_offset_minutes integer,
        ADD COLUMN IF NOT EXISTS rule_export_close_offset_minutes integer;
    `);
  }

  public async down(queryRunner: QueryRunner): Promise<void> {
    await queryRunner.query(`
      ALTER TABLE freight.train_schedules
        DROP COLUMN IF EXISTS rule_import_close_offset_minutes,
        DROP COLUMN IF EXISTS rule_export_close_offset_minutes;
    `);
    await queryRunner.query(`
      ALTER TABLE freight.train_scheduling_global_rules
        DROP COLUMN IF EXISTS import_close_offset_minutes,
        DROP COLUMN IF EXISTS export_close_offset_minutes;
    `);
  }
}
