/**
 * MIXED IMPORT journey M1 — containers AND bulk wheat share ONE 54-wagon
 * import train on the corridor DJIB_PORT → … → KALITY. The route-day pool is
 * type-blind: one window, one doc-review, ONE batch reserves all six; only
 * wagon allocation cares about the physical type — containers ride NW5 flat
 * wagons, wheat rides CW4 covered gondolas, never crossed.
 *
 * The six bookings (Σ = 54 wagons):
 *   MC1  container  customs + USD   16×20ft =  8 × NW5
 *   MB1  bulk       customs + USD     560 T =  8 × CW4
 *   MC2  container  self    + ETB    6×40ft =  6 × NW5
 *   MB2  bulk       self    + ETB     980 T = 14 × CW4
 *   MC3  container  customs + ETB   16×20ft =  8 × NW5
 *   MB3  bulk       self    + USD     700 T = 10 × CW4
 *
 * Sequential steps of one journey — retries off.
 */

import {
  acceptOperation,
  apiPost,
  bookBulk,
  bookContainers,
  closeBookingWindow,
  completeBookingMilestone,
  completeDocReview,
  createImportSchedule,
  db,
  departureAt,
  eatDayStr,
  endPaymentPhase,
  ensureCorridorRoute,
  expectMilestoneDone,
  expectWagonType,
  forceWindowOpen,
  glUpload,
  markPaid,
  opsStaff,
  pollAllocations,
  pollBookingStatus,
  pollDb,
  resetCorridorDay,
  seedImportContract,
  withBooking,
  withSchedule,
  type ScheduleRow,
} from "./import-utils";

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

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

const BOOKINGS: Array<{
  suffix: string;
  freight: "CONTAINER" | "BULK";
  customs: boolean;
  currency: "ETB" | "USD";
  twenty?: number;
  forty?: number;
  tons?: number;
  wagons: number;
}> = [
  { suffix: "MC1", freight: "CONTAINER", customs: true, currency: "USD", twenty: 16, wagons: 8 },
  { suffix: "MB1", freight: "BULK", customs: true, currency: "USD", tons: 560, wagons: 8 },
  { suffix: "MC2", freight: "CONTAINER", customs: false, currency: "ETB", forty: 6, wagons: 6 },
  { suffix: "MB2", freight: "BULK", customs: false, currency: "ETB", tons: 980, wagons: 14 },
  { suffix: "MC3", freight: "CONTAINER", customs: true, currency: "ETB", twenty: 16, wagons: 8 },
  { suffix: "MB3", freight: "BULK", customs: false, currency: "USD", tons: 700, wagons: 10 },
];
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) {
  withSchedule(DEPARTURE, (s) => fn(s.id, s));
}

describe("mixed import: containers and wheat share one 54-wagon train", { 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,
        freight: b.freight,
      });
    }
  });

  it("operations prepares the corridor and one 54-wagon train — first window forced open", () => {
    ensureCorridorRoute();
    resetCorridorDay(DEPARTURE);
    createImportSchedule({ departure: DEPARTURE, locoPair: ["LOCO-IMP-1", "LOCO-IMP-2"] });
    withScheduleId((id) => forceWindowOpen(id, 45));
  });

  it("three container and three bulk shipments book inside the same first window", () => {
    let isoSeed = 9000;
    BOOKINGS.forEach((b) => {
      if (b.freight === "CONTAINER") {
        bookContainers({
          suffix: b.suffix,
          runStamp: stamp,
          isoSeed,
          twenty: b.twenty,
          forty: b.forty,
          scheduledDate: BOOKING_DAY,
        });
        isoSeed += (b.twenty ?? 0) + (b.forty ?? 0);
      } else {
        bookBulk({ suffix: b.suffix, tons: b.tons!, scheduledDate: BOOKING_DAY });
      }
      pollBookingStatus(b.suffix, "OPERATION_REQUEST_PENDING", 5);
    });
  });

  it("operations accepts all six — one type-blind pool", () => {
    BOOKINGS.forEach((b) => acceptOperation(b.suffix));
  });

  it("ONE doc-review-complete releases ONE batch that reserves both cargo kinds together", () => {
    withScheduleId((id) => {
      closeBookingWindow(id);
      completeDocReview(id);
    });
    BOOKINGS.forEach((b) =>
      pollBookingStatus(b.suffix, ["SELECTED_FOR_BATCH", "AWAITING_PAYMENT"]),
    );
    // Currency mix from one batch: USD and ETB invoices side by side.
    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 — 54/54 with STRICT wagon-type integrity (containers on NW5, wheat on CW4)", () => {
    BOOKINGS.forEach((b) => {
      markPaid(b.suffix);
      pollAllocations(b.suffix, b.wagons);
    });
    BOOKINGS.forEach((b) =>
      expectWagonType(b.suffix, b.freight === "CONTAINER" ? "NW5" : "CW4", b.wagons),
    );
    withScheduleId((id) => {
      endPaymentPhase(id);
      pollDb<ScheduleRow>(
        "schedule FULL + DONE + finalized",
        `SELECT window_phase, booking_window_status, status
         FROM freight.train_schedules WHERE id = $1`,
        [id],
        (s) =>
          s?.booking_window_status === "FULL" &&
          s?.window_phase === "DONE" &&
          s?.status === "SCHEDULED",
      );
      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));
    });
  });

  it("gate pass + T1 uploads for the customs bookings of BOTH kinds", () => {
    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}/t1-documents`);
      });
    });
  });

  it("the mixed train dispatches, runs the corridor and arrives — both kinds ARRIVED", () => {
    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,
      );
      [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("the customs tails of container AND bulk bookings complete side by side", () => {
    CUSTOMS.forEach((suffix) => {
      withBooking(suffix, (b) => {
        apiPost("superadmin@tria.com", `/api/contracts/bookings/${b.id}/t1-close`)
          .its("status")
          .should("be.oneOf", [200, 201]);
        apiPost("superadmin@tria.com", `/api/contracts/bookings/${b.id}/risk`, {
          riskLevel: "GREEN",
        })
          .its("status")
          .should("be.oneOf", [200, 201]);
        glUpload(
          `/api/contracts/bookings/${b.id}/second-duty`,
          { dutyRequired: "false" },
          "attachment",
        );
      });
      completeBookingMilestone(suffix, "IMPORT_RELEASE_GRANTED");
      expectMilestoneDone(suffix, "T1_CLOSED");
      expectMilestoneDone(suffix, "IMPORT_RELEASE_GRANTED");
    });
    SELF_CLEAR.forEach((suffix) => {
      withBooking(suffix, (b) => {
        expect(b.status, `${suffix} arrived clean`).to.eq("ARRIVED");
      });
    });
  });
});

export {};
