import type { Freight } from "@edr/types";

import { contractNeedsClearanceAction } from "@/components/customer-actions/deriveContractCustomerAction";

/** A pending customer action surfaced on the home "needs attention" card. */
export interface ActionItem {
  id: string;
  /** What the customer must do — drives the icon, label and modal. */
  kind: "clearance" | "duty" | "sign" | "book" | "pay";
  /** The contract/booking reference for display. */
  reference: string;
  /** Short human description of the action. */
  description: string;
  /** Contract id (clearance/sign/book) or booking id (pay). */
  targetId: string;
  /** True for queried clearance (a document was sent back for correction). */
  urgent?: boolean;
}

/**
 * Derive the list of pending customer actions from the customer's contracts and
 * bookings. A contract in AWAITING_CLEARANCE_DOCUMENTS (initial upload or a
 * re-upload after a query) is flagged urgent so the home card shows an upload
 * button. See {@link contractNeedsClearanceAction}.
 */
export function deriveActionItems(
  contracts: Freight.IContract[],
  bookings: Freight.IBooking[],
): ActionItem[] {
  const items: ActionItem[] = [];

  for (const c of contracts) {
    if (c.status === "CONTRACT_READY") {
      items.push({
        id: `sign-${c.id}`,
        kind: "sign",
        reference: c.reference,
        description: "Contract ready to sign",
        targetId: c.id,
      });
      continue;
    }
    const clr = contractNeedsClearanceAction(c);
    if (clr.show) {
      items.push({
        id: `clearance-${c.id}`,
        kind: "clearance",
        reference: c.reference,
        description: clr.urgent
          ? "Clearance documents need your action"
          : "Clearance under review",
        targetId: c.id,
        urgent: clr.urgent,
      });
      continue;
    }
    // Path A transport-only: customer may create the shipment booking.
    if (
      !c.customsClearingEnabled &&
      (c.status === "FULLY_EXECUTED" || c.status === "CONTRACT_ACTIVE")
    ) {
      items.push({
        id: `book-${c.id}`,
        kind: "book",
        reference: c.reference,
        description: "Ready to book a shipment",
        targetId: c.id,
      });
    }
  }

  for (const b of bookings) {
    const isGeneral = b.bookingType === "GENERAL_CONTRACT";
    const canPay =
      b.paymentStatus !== "PAID" &&
      (isGeneral
        ? b.status === "FULLY_EXECUTED"
        : b.status === "SELECTED_FOR_BATCH");
    if (canPay) {
      items.push({
        id: `pay-${b.id}`,
        kind: "pay",
        reference: b.reference,
        description: "Payment due for this shipment",
        targetId: b.id,
        urgent: true,
      });
    }
  }

  // Surface the most pressing (urgent) actions first.
  return items.sort((a, b) => Number(b.urgent ?? 0) - Number(a.urgent ?? 0));
}
