import type { TruckLaneScheduleResponse } from "@/app/api/shop/actions";

const DEFAULT_LIST_LIMIT = 200;

export function buildTruckLaneScheduleListQuery(
  status?: string[],
  limit: number = DEFAULT_LIST_LIMIT,
): string {
  const params = new URLSearchParams();
  for (const s of status ?? []) {
    params.append("status", s);
  }
  params.set("limit", String(limit));
  const qs = params.toString();
  return qs ? `?${qs}` : "";
}

export function collectFailedTruckRowIdsFromSchedules(
  schedules: TruckLaneScheduleResponse[],
  lineDetails: Array<TruckLaneScheduleResponse | null | undefined>,
): Set<number> {
  const out = new Set<number>();
  for (const detail of lineDetails) {
    for (const line of detail?.lines ?? []) {
      if (line.lineStatus === "FAILED" && line.truckRowId != null && line.truckRowId > 0) {
        out.add(line.truckRowId);
      }
    }
  }
  for (const schedule of schedules) {
    if (
      schedule.status === "FAILED" &&
      (schedule.lineCounts?.failed ?? 0) > 0 &&
      !lineDetails.some((d) => d?.id === schedule.id)
    ) {
      // header-only failure without warmed lines — no shop ids available
    }
  }
  return out;
}

export function filterFailedSchedules(
  schedules: TruckLaneScheduleResponse[],
): TruckLaneScheduleResponse[] {
  return schedules.filter(
    (s) =>
      s.status !== "IGNORED" &&
      (s.status === "FAILED" ||
        (s.status === "PARTIAL" && (s.lineCounts?.failed ?? 0) > 0)),
  );
}

export function extractApiErrorMessage(err: unknown): string | null {
  if (err instanceof Error && err.message.trim()) return err.message.trim();
  if (typeof err === "string" && err.trim()) return err.trim();
  return null;
}
