import type { PoResult } from "@/app/api/po";
import type { PoWorkbenchListRow } from "@/components/PoWorkbench/types";

const RECEIVE_STATUSES = new Set(["pending", "receiving", "completed"]);

function normalizeReceiveStatus(status: string): PoWorkbenchListRow["status"] {
  if (RECEIVE_STATUSES.has(status)) {
    return status as PoWorkbenchListRow["status"];
  }
  return "pending";
}

function pad2(n: number): string {
  return n < 10 ? `0${n}` : String(n);
}

/**
 * Normalizes backend date values into `YYYY-MM-DD`.
 * Supports both ISO strings and Jackson-style arrays (`[yyyy, mm, dd, ...]`).
 */
function toYmd(value: unknown): string {
  if (value == null) {
    return "";
  }

  if (Array.isArray(value)) {
    const y = Number(value[0]);
    const m = Number(value[1]);
    const d = Number(value[2]);
    if (
      Number.isInteger(y) &&
      Number.isInteger(m) &&
      Number.isInteger(d) &&
      y > 0 &&
      m >= 1 &&
      m <= 12 &&
      d >= 1 &&
      d <= 31
    ) {
      return `${y}-${pad2(m)}-${pad2(d)}`;
    }
    return "";
  }

  if (typeof value !== "string") {
    return "";
  }

  const t = value.trim();
  if (t.length >= 10 && /^\d{4}-\d{2}-\d{2}/.test(t)) {
    return t.slice(0, 10);
  }
  return t;
}

/** Maps one PO list API row into the shape the workbench list UI already expects. */
export function mapPoResultToListRow(po: PoResult): PoWorkbenchListRow {
  return {
    id: String(po.id),
    poNumber: po.code,
    supplierName: po.supplier ?? "",
    orderDate: toYmd(po.orderDate),
    estimatedArrivalDate: toYmd(po.estimatedArrivalDate),
    escalated: Boolean(po.escalated),
    status: normalizeReceiveStatus(po.status ?? ""),
  };
}
