"use client";

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

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

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

export async function fetchTruckRoutingStoreOptions(): Promise<ReportOption[]> {
  const response = await clientAuthFetch(
    `${NEXT_PUBLIC_API_URL}/truck-routing-summary/store-options`,
    {
      method: "GET",
      headers: { "Content-Type": "application/json" },
    }
  );

  if (!response.ok) {
    throw new Error(`Failed to fetch 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 fetchTruckRoutingLaneOptions(storeId?: string): Promise<ReportOption[]> {
  const qs = storeId ? `?storeId=${encodeURIComponent(storeId)}` : "";
  const response = await clientAuthFetch(
    `${NEXT_PUBLIC_API_URL}/truck-routing-summary/lane-options${qs}`,
    {
      method: "GET",
      headers: { "Content-Type": "application/json" },
    }
  );

  if (!response.ok) {
    throw new Error(`Failed to fetch 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 fetchTruckRoutingSummaryPrecheck(params: {
  storeId: string;
  truckLanceCode: string;
  date: string;
}): Promise<TruckRoutingSummaryPrecheck> {
  const qs = new URLSearchParams({
    storeId: params.storeId,
    truckLanceCode: params.truckLanceCode,
    date: params.date,
  }).toString();
  const response = await clientAuthFetch(
    `${NEXT_PUBLIC_API_URL}/truck-routing-summary/precheck?${qs}`,
    {
      method: "GET",
      headers: { "Content-Type": "application/json" },
    }
  );
  if (!response.ok) {
    throw new Error(`Failed to precheck routing summary: ${response.status}`);
  }
  const data = await response.json();
  return {
    unpickedOrderCount: Number(data?.unpickedOrderCount ?? 0),
    hasUnpickedOrders: Boolean(data?.hasUnpickedOrders),
  };
}
