/**
 * BULK EXPORT journey — six wheat bookings fill the 54-wagon CW4 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.
 *
 * The six bookings (70 T per CW4 wagon — Σ = 54 wagons / 3 780 T):
 *   XBF1  customs + USD    560 T =  8 wagons
 *   XBF2  customs + ETB    420 T =  6 wagons
 *   XBF3  self    + ETB    420 T =  6 wagons
 *   XBF4  self    + ETB    420 T =  6 wagons
 *   XBF5  customs + USD  1 540 T = 22 wagons  (the ≥22-wagon giant)
 *   XBF6  self    + USD    420 T =  6 wagons
 *
 * Sequential steps of one journey — retries off.
 */

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

const DEPARTURE = departureAt(8);
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";
  tons: number;
  wagons: number;
}> = [
  { suffix: "XBF1", customs: true, currency: "USD", tons: 560, wagons: 8 },
  { suffix: "XBF2", customs: true, currency: "ETB", tons: 420, wagons: 6 },
  { suffix: "XBF3", customs: false, currency: "ETB", tons: 420, wagons: 6 },
  { suffix: "XBF4", customs: false, currency: "ETB", tons: 420, wagons: 6 },
  { suffix: "XBF5", customs: true, currency: "USD", tons: 1540, wagons: 22 },
  { suffix: "XBF6", customs: false, currency: "USD", tons: 420, 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("bulk export: six wheat bookings fill the 54-wagon CW4 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,
        freight: "BULK",
        direction: "EXPORT",
        originCode: EXP_ORIGIN,
        destCode: EXP_DEST,
      });
    }
  });

  it("operations prepares the export corridor and a 54-wagon CW4 train — window forced open", () => {
    ensureExportRoute();
    resetCorridorDay(DEPARTURE, EXP_DEST, EXP_ORIGIN);
    createImportSchedule({
      departure: DEPARTURE,
      locoPair: ["LOCO-EXP-1", "LOCO-EXP-2"],
      kind: "bulk",
      originCode: EXP_ORIGIN,
      destCode: EXP_DEST,
    });
    withScheduleId((id) => forceWindowOpen(id, 60));
  });

  it("six exporters book wheat inside the one window", () => {
    BOOKINGS.forEach((b) => {
      bookBulk({ suffix: b.suffix, tons: b.tons, scheduledDate: BOOKING_DAY });
      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());
        });
      });
    });
    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));
      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 + T1 uploads, the train dispatches and runs the corridor to Djibouti Port", () => {
    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`);
      });
    });

    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));
  });

  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 {};
