import type { PoWorkbenchAdvancedFilters } from "@/components/PoWorkbench/types";
import { trimString } from "@/components/PoWorkbench/workbenchUtils";

/** Rows per request; keeps the results list DOM small until the user scrolls. */
export const PO_WORKBENCH_LIST_PAGE_SIZE = 50;

/**
 * Builds GET /po/list query params for the PO Workbench.
 * Same contract as the legacy Po search screen (CriteriaArgsBuilder on the server).
 */
export function buildWorkbenchPoListSearchParams(
  poNumber: string,
  advanced: PoWorkbenchAdvancedFilters,
  pageNum: number,
  pageSize: number,
): URLSearchParams {
  const params = new URLSearchParams();
  params.set("pageNum", String(pageNum));
  params.set("pageSize", String(pageSize));

  const code = trimString(poNumber);
  if (code) {
    params.set("code", code);
  }

  const supplier = trimString(advanced.supplierQuery);
  if (supplier) {
    params.set("supplier", supplier);
  }

  const orderDateFrom = trimString(advanced.orderDateFrom);
  if (orderDateFrom) {
    params.set("orderDate", orderDateFrom);
  }
  const orderDateTo = trimString(advanced.orderDateTo);
  if (orderDateTo) {
    params.set("orderDateTo", orderDateTo);
  }
  const etaDateFrom = trimString(advanced.etaDateFrom);
  if (etaDateFrom) {
    params.set("estimatedArrivalDate", etaDateFrom);
  }
  const etaDateTo = trimString(advanced.etaDateTo);
  if (etaDateTo) {
    params.set("estimatedArrivalDateTo", etaDateTo);
  }

  if (advanced.reportStatus === "ESCALATED") {
    params.set("escalated", "true");
  } else if (advanced.reportStatus === "NOT_ESCALATED") {
    params.set("escalated", "false");
  }

  if (advanced.receiveStatus !== "ALL") {
    params.set("status", advanced.receiveStatus);
  }

  return params;
}
