/**
 * BULK IMPORT journey 1 — six wheat bookings fill a 54-wagon CW4 train on the
 * long corridor DJIB_PORT → NAGAD → DIRE_DAWA → E2E_AWASH → MOJO → KALITY,
 * all in the FIRST booking window, then the full life of the train: payment,
 * allocation, gate pass, T1, dispatch, checkpoint-by-checkpoint movement,
 * arrival, and the post-arrival customs tail.
 *
 * The six bookings (70 T per CW4 wagon — Σ = 54 wagons / 3 780 T):
 *   BF1  customs + USD    560 T =  8 wagons
 *   BF2  customs + ETB    420 T =  6 wagons
 *   BF3  self    + ETB    420 T =  6 wagons
 *   BF4  self    + ETB    420 T =  6 wagons
 *   BF5  customs + USD  1 540 T = 22 wagons  (the ≥22-wagon giant)
 *   BF6  self    + USD    420 T =  6 wagons
 *
 * Sequential steps of one journey — retries off.
 */

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

const DEPARTURE = departureAt(10);
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: "BF1", customs: true, currency: "USD", tons: 560, wagons: 8 },
  { suffix: "BF2", customs: true, currency: "ETB", tons: 420, wagons: 6 },
  { suffix: "BF3", customs: false, currency: "ETB", tons: 420, wagons: 6 },
  { suffix: "BF4", customs: false, currency: "ETB", tons: 420, wagons: 6 },
  { suffix: "BF5", customs: true, currency: "USD", tons: 1540, wagons: 22 },
  { suffix: "BF6", 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) {
  withSchedule(DEPARTURE, (s) => fn(s.id, s));
}

describe("bulk import: six wheat bookings fill the 54-wagon CW4 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: "BULK",
      });
    }
  });

  it("operations prepares the corridor and a 54-wagon BULK train — first window forced open", () => {
    ensureCorridorRoute();
    resetCorridorDay(DEPARTURE);
    createImportSchedule({
      departure: DEPARTURE,
      locoPair: ["LOCO-IMP-15", "LOCO-IMP-16"],
      kind: "bulk",
    });
    withScheduleId((id) => forceWindowOpen(id, 45));
    withScheduleId((_, s) => {
      expect(s.booking_cycle_no, "FIRST window cycle").to.eq(1);
    });
  });

  it("customer books all six wheat shipments inside the first window", () => {
    BOOKINGS.forEach((b) => {
      bookBulk({ suffix: b.suffix, tons: b.tons, scheduledDate: BOOKING_DAY });
      pollBookingStatus(b.suffix, "OPERATION_REQUEST_PENDING", 5);
    });
  });

  it("operations accepts all six — the whole pool is FULLY_EXECUTED (in window)", () => {
    BOOKINGS.forEach((b) => acceptOperation(b.suffix));
  });

  it("window closes, doc review completes — the batch reserves ALL six (they fit exactly)", () => {
    withScheduleId((id) => {
      closeBookingWindow(id);
      completeDocReview(id);
    });
    BOOKINGS.forEach((b) =>
      pollBookingStatus(b.suffix, ["SELECTED_FOR_BATCH", "AWAITING_PAYMENT"]),
    );
    BOOKINGS.forEach((b) => {
      withBooking(b.suffix, (row) => {
        expect(row.payment_deadline, `${b.suffix} pay deadline`).to.be.a("string");
        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 onto the train, 54/54 wagons, window FULL and schedule finalized", () => {
    BOOKINGS.forEach((b) => {
      markPaid(b.suffix);
      pollAllocations(b.suffix, 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("GL Djibouti: gate pass granted, 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}/t1-documents`);
      });
    });
  });

  it("the train dispatches and runs the corridor checkpoint by checkpoint to the terminal", () => {
    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));

    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 runs the customs tail on every customs booking (T1 close → risk → second duty → release → final invoice)", () => {
    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",
        );
        glUpload(
          `/api/contracts/bookings/${b.id}/final-invoice`,
          { amount: "1000", description: "e2e final invoice" },
          "file",
        );
        glUpload(`/api/contracts/bookings/${b.id}/final-invoice-slip`, {}, "file");
        apiPost(
          "superadmin@tria.com",
          `/api/contracts/bookings/${b.id}/final-invoice/confirm`,
        )
          .its("status")
          .should("be.oneOf", [200, 201]);
      });
      completeBookingMilestone(suffix, "IMPORT_RELEASE_GRANTED");
      completeBookingMilestone(suffix, "IMPORT_PROCESS_COMPLETED");
      expectMilestoneDone(suffix, "T1_CLOSED");
      expectMilestoneDone(suffix, "RISK_ASSIGNED");
      expectMilestoneDone(suffix, "IMPORT_RELEASE_GRANTED");
      expectMilestoneDone(suffix, "IMPORT_PROCESS_COMPLETED");
    });
  });

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