"use client";

import { clientAuthFetch } from "@/app/utils/clientAuthFetch";
import { NEXT_PUBLIC_API_URL } from "@/config/api";

export interface WorkbenchReportOption {
  label: string;
  value: string;
}

export interface WorkbenchTruckRoutingSummaryPrecheck {
  unpickedOrderCount: number;
  hasUnpickedOrders: boolean;
}

export async function fetchWorkbenchTruckRoutingStoreOptions(): Promise<WorkbenchReportOption[]> {
  const response = await clientAuthFetch(
    `${NEXT_PUBLIC_API_URL}/doPickOrder/workbench/truck-routing-summary/store-options`,
    {
      method: "GET",
      headers: { "Content-Type": "application/json" },
    }
  );
  if (!response.ok) throw new Error(`Failed to fetch workbench store options: ${response.status}`);
  const data = await response.json();
  if (!Array.isArray(data)) return [];
  return data.map((item: any) => ({
    label: item?.label ?? item?.value ?? "",
    value: item?.value ?? "",
  }));
}

export async function fetchWorkbenchTruckRoutingLaneOptions(storeId?: string): Promise<WorkbenchReportOption[]> {
  const qs = storeId ? `?storeId=${encodeURIComponent(storeId)}` : "";
  const response = await clientAuthFetch(
    `${NEXT_PUBLIC_API_URL}/doPickOrder/workbench/truck-routing-summary/lane-options${qs}`,
    {
      method: "GET",
      headers: { "Content-Type": "application/json" },
    }
  );
  if (!response.ok) throw new Error(`Failed to fetch workbench lane options: ${response.status}`);
  const data = await response.json();
  if (!Array.isArray(data)) return [];
  return data.map((item: any) => ({
    label: item?.label ?? item?.value ?? "",
    value: item?.value ?? "",
  }));
}

export async function fetchWorkbenchTruckRoutingSummaryPrecheck(params: {
  storeId: string;
  truckLanceCode: string;
  date: string;
}): Promise<WorkbenchTruckRoutingSummaryPrecheck> {
  const qs = new URLSearchParams({
    storeId: params.storeId,
    truckLanceCode: params.truckLanceCode,
    date: params.date,
  }).toString();
  const response = await clientAuthFetch(
    `${NEXT_PUBLIC_API_URL}/doPickOrder/workbench/truck-routing-summary/precheck?${qs}`,
    {
      method: "GET",
      headers: { "Content-Type": "application/json" },
    }
  );
  if (!response.ok) throw new Error(`Failed to precheck workbench routing summary: ${response.status}`);
  const data = await response.json();
  return {
    unpickedOrderCount: Number(data?.unpickedOrderCount ?? 0),
    hasUnpickedOrders: Boolean(data?.hasUnpickedOrders),
  };
}
