/**
 * EXPORT journey E1 — six container bookings fill the 54-wagon train on the
 * reversed corridor KALITY → MOJO → E2E_AWASH → DIRE_DAWA → NAGAD →
 * DJIB_PORT, all inside the ONE FCFS export window, then the full life of the
 * train to Djibouti Port and the export customs tail.
 *
 * Export mechanics under test (vs import): no cycles, no doc-review/payment
 * phases, no batch — the ops ACCEPT itself reserves the wagons FCFS and opens
 * a pay window CLAMPED to the window close.
 *
 * The six bookings (Σ = 54 wagons):
 *   EF1  customs + USD   16×20ft            =  8 wagons
 *   EF2  customs + ETB    6×40ft            =  6 wagons
 *   EF3  self    + ETB   12×20ft            =  6 wagons
 *   EF4  self    + ETB    6×40ft            =  6 wagons
 *   EF5  customs + USD   44×20ft            = 22 wagons  (the ≥22-wagon giant)
 *   EF6  self    + USD    4×40ft + 4×20ft   =  6 wagons
 *
 * Sequential steps of one journey — retries off.
 */

import {
  acceptExport,
  apiPost,
  bookContainers,
  createImportSchedule,
  db,
  dbBooking,
  departureAt,
  eatDayStr,
  ensureExportRoute,
  EXP_DEST,
  EXP_ORIGIN,
  expectMilestoneDone,
  completeBookingMilestone,
  forceWindowOpen,
  glUpload,
  markPaid,
  opsStaff,
  pollAllocations,
  pollBookingStatus,
  pollDb,
  resetCorridorDay,
  seedImportContract,
  withBooking,
  withExportSchedule,
  type ScheduleRow,
} from "./import-utils";

const DEPARTURE = departureAt(2);
const BOOKING_DAY = eatDayStr(DEPARTURE);

const stamp = String(Date.now());
const stampedRef = (suffix: string) => `CTR-IMP-${stamp}-${suffix}`;

const BOOKINGS: Array<{
  suffix: string;
  customs: boolean;
  currency: "ETB" | "USD";
  twenty: number;
  forty: number;
  wagons: number;
}> = [
  { suffix: "EF1", customs: true, currency: "USD", twenty: 16, forty: 0, wagons: 8 },
  { suffix: "EF2", customs: true, currency: "ETB", twenty: 0, forty: 6, wagons: 6 },
  { suffix: "EF3", customs: false, currency: "ETB", twenty: 12, forty: 0, wagons: 6 },
  { suffix: "EF4", customs: false, currency: "ETB", twenty: 0, forty: 6, wagons: 6 },
  { suffix: "EF5", customs: true, currency: "USD", twenty: 44, forty: 0, wagons: 22 },
  { suffix: "EF6", customs: false, currency: "USD", twenty: 4, forty: 4, wagons: 6 },
];
const CUSTOMS = BOOKINGS.filter((b) => b.customs).map((b) => b.suffix);
const SELF_CLEAR = BOOKINGS.filter((b) => !b.customs).map((b) => b.suffix);

function withScheduleId(fn: (id: string, s: ScheduleRow) => void) {
  withExportSchedule(DEPARTURE, (s) => fn(s.id, s));
}

describe("export: six bookings fill the 54-wagon corridor train (FCFS)", { retries: 0 }, () => {
  before(() => {
    cy.task("db:seedFile", "seed-import-corridor.sql");
    for (const b of BOOKINGS) {
      seedImportContract({
        suffix: b.suffix,
        reference: stampedRef(b.suffix),
        currency: b.currency,
        customs: b.customs,
        direction: "EXPORT",
        originCode: EXP_ORIGIN,
        destCode: EXP_DEST,
      });
    }
  });

  it("operations ensures the reversed export corridor exists (direction frozen EXPORT)", () => {
    ensureExportRoute();
    resetCorridorDay(DEPARTURE, EXP_DEST, EXP_ORIGIN);
  });

  it("operations schedules the 54-wagon export train — its single FCFS window forced open", () => {
    createImportSchedule({
      departure: DEPARTURE,
      locoPair: ["LOCO-EXP-1", "LOCO-EXP-2"],
      originCode: EXP_ORIGIN,
      destCode: EXP_DEST,
    });
    withScheduleId((id) => forceWindowOpen(id, 60));
  });

  it("six exporters book inside the one window", () => {
    let isoSeed = 6000;
    BOOKINGS.forEach((b) => {
      bookContainers({
        suffix: b.suffix,
        runStamp: stamp,
        isoSeed,
        twenty: b.twenty,
        forty: b.forty,
        scheduledDate: BOOKING_DAY,
      });
      isoSeed += b.twenty + b.forty;
      pollBookingStatus(b.suffix, "OPERATION_REQUEST_PENDING", 5);
    });
  });

  it("each accept reserves FCFS immediately — pay deadlines clamped to the window close", () => {
    BOOKINGS.forEach((b) => acceptExport(b.suffix));
    withScheduleId((_, s) => {
      BOOKINGS.forEach((b) => {
        withBooking(b.suffix, (row) => {
          expect(row.payment_deadline, `${b.suffix} pay deadline`).to.be.a("string");
          expect(
            new Date(row.payment_deadline!).getTime(),
            `${b.suffix} deadline never outlives the window close`,
          ).to.be.at.most(new Date(s.window_closes_at!).getTime());
        });
      });
    });
    // Reservation invoices carry the CONTRACT currency.
    BOOKINGS.forEach((b) => {
      withBooking(b.suffix, (row) => {
        pollDb<{ currency: string }>(
          `${b.suffix} invoice`,
          `SELECT currency FROM freight.invoices
           WHERE source_id = $1 AND deleted_at IS NULL
           ORDER BY created_at DESC LIMIT 1`,
          [row.id],
          (inv) => inv?.currency === b.currency,
          10,
        );
      });
    });
  });

  it("all six pay — allocated 54/54, the export window flips FULL, staff finalize", () => {
    BOOKINGS.forEach((b) => {
      markPaid(b.suffix);
      pollAllocations(b.suffix, b.wagons);
    });
    withScheduleId((id) => {
      pollDb<ScheduleRow>(
        "export window FULL",
        `SELECT booking_window_status FROM freight.train_schedules WHERE id = $1`,
        [id],
        (s) => s?.booking_window_status === "FULL",
      );
      db<{ n: string }>(
        `SELECT count(DISTINCT wba.train_set_wagon_id) AS n
         FROM freight.wagon_booking_allocations wba
         JOIN freight.train_schedule_bookings tsb
           ON tsb.booking_id = wba.booking_id AND tsb.train_schedule_id = $1
         WHERE wba.deleted_at IS NULL AND tsb.deleted_at IS NULL`,
        [id],
      ).then(({ rows }) => expect(Number(rows[0].n), "54 wagons allocated").to.eq(54));
      // Export has no auto-finalize conclude step — staff finalize explicitly.
      apiPost(opsStaff, `/api/train-scheduling/schedules/${id}/finalize`)
        .its("status")
        .should("be.oneOf", [200, 201]);
      pollDb<ScheduleRow>(
        "schedule SCHEDULED",
        `SELECT status FROM freight.train_schedules WHERE id = $1`,
        [id],
        (s) => s?.status === "SCHEDULED",
        10,
      );
    });
  });

  it("gate pass granted at the Djibouti end; T1 documents uploaded for the customs bookings", () => {
    withScheduleId((id) => {
      apiPost(opsStaff, `/api/train-scheduling/schedules/${id}/import-djibouti/gatepass-granted`)
        .its("status")
        .should("be.oneOf", [200, 201]);
    });
    CUSTOMS.forEach((suffix) => {
      withBooking(suffix, (b) => {
        glUpload(`/api/contracts/bookings/${b.id}/transport-document`);
      });
    });
  });

  it("the train dispatches — every booking boards at KALITY (IN_TRANSIT)", () => {
    withScheduleId((id) => {
      apiPost(opsStaff, `/api/train-scheduling/schedules/${id}/dispatch`)
        .its("status")
        .should("be.oneOf", [200, 201]);
      pollDb<ScheduleRow>(
        "schedule DISPATCHED",
        `SELECT status FROM freight.train_schedules WHERE id = $1`,
        [id],
        (s) => s?.status === "DISPATCHED",
        10,
      );
    });
    BOOKINGS.forEach((b) => pollBookingStatus(b.suffix, "IN_TRANSIT", 10));
  });

  it("the train runs the corridor and arrives at Djibouti Port — every booking ARRIVED", () => {
    withScheduleId((id) => {
      [1, 2, 3, 4].forEach((seq) => {
        apiPost(opsStaff, `/api/train-scheduling/schedules/${id}/checkpoints`, {
          sequenceNo: seq,
          kind: "PASSED",
        })
          .its("status")
          .should("be.oneOf", [200, 201]);
      });
      apiPost(opsStaff, `/api/train-scheduling/schedules/${id}/checkpoints`, {
        sequenceNo: 5,
        kind: "ARRIVED",
      })
        .its("status")
        .should("be.oneOf", [200, 201]);
      pollDb<ScheduleRow>(
        "schedule ARRIVED",
        `SELECT status FROM freight.train_schedules WHERE id = $1`,
        [id],
        (s) => s?.status === "ARRIVED",
        20,
      );
    });
    BOOKINGS.forEach((b) => pollBookingStatus(b.suffix, "ARRIVED", 20));
    withScheduleId((id) => {
      db<{ n: string }>(
        `SELECT count(*) AS n FROM freight.wagon_movements
         WHERE train_schedule_id = $1`,
        [id],
      ).then(({ rows }) =>
        expect(Number(rows[0].n), "wagon movement ledger rows").to.be.at.least(54),
      );
    });
  });

  it("GL Djibouti closes the export tail (T1 close → offloaded) on every customs booking", () => {
    CUSTOMS.forEach((suffix) => {
      withBooking(suffix, (b) => {
        apiPost("superadmin@tria.com", `/api/contracts/bookings/${b.id}/t1-close`)
          .its("status")
          .should("be.oneOf", [200, 201]);
      });
      completeBookingMilestone(suffix, "OFFLOADED");
      expectMilestoneDone(suffix, "T1_CLOSED");
      expectMilestoneDone(suffix, "OFFLOADED");
    });
  });

  it("the self-clearance bookings arrived clean — no customs tail required", () => {
    SELF_CLEAR.forEach((suffix) => {
      withBooking(suffix, (b) => {
        expect(b.status, `${suffix} final status`).to.eq("ARRIVED");
      });
      dbBooking(suffix).then(({ rows }) => {
        db<{ n: string }>(
          `SELECT count(*) AS n FROM freight.clearance_milestones
           WHERE booking_id = $1 AND milestone_code = 'T1_CLOSED'
             AND status = 'COMPLETED' AND deleted_at IS NULL`,
          [rows[0].id],
        ).then(({ rows: ms }) =>
          expect(Number(ms[0].n), `${suffix} has no T1 tail`).to.eq(0),
        );
      });
    });
  });
});

export {};
