"use server";

import { BASE_API_URL } from "@/config/api";
import { serverFetchJson } from "@/app/utils/fetchUtil";
import { revalidateTag } from "next/cache";
import { cache } from "react";

export interface ItemOrderItem {
  id: number;
  code: string;
  name: string;
  itemOrder: number | null;
  storeId?: string | null;
  warehouse?: string | null;
  area?: string | null;
  slot?: string | null;
  locationCode?: string | null;
}

export const fetchOrderedItemOrderItems = cache(async (search?: string): Promise<ItemOrderItem[]> => {
  const params = new URLSearchParams();
  if (search?.trim()) params.set("search", search.trim());
  // Optional filtering by item type (e.g. fg)
  const url = `${BASE_API_URL}/items/itemOrder/ordered${params.toString() ? `?${params.toString()}` : ""}`;
  const res = await serverFetchJson<ItemOrderItem[]>(url, { method: "GET", next: { tags: ["itemOrder"] } });
  return res ?? [];
});

export const fetchUnorderedItemOrderItems = cache(async (search?: string, type?: string): Promise<ItemOrderItem[]> => {
  const params = new URLSearchParams();
  if (search?.trim()) params.set("search", search.trim());
  if (type?.trim()) params.set("type", type.trim());
  const url = `${BASE_API_URL}/items/itemOrder/unordered${params.toString() ? `?${params.toString()}` : ""}`;
  const res = await serverFetchJson<ItemOrderItem[]>(url, { method: "GET", next: { tags: ["itemOrder"] } });
  return res ?? [];
});

export const searchUnorderedItemOrderItems = cache(
  async (search: string, type?: string, limit: number = 200): Promise<ItemOrderItem[]> => {
    const params = new URLSearchParams();
    params.set("search", search.trim());
    if (type?.trim()) params.set("type", type.trim());
    params.set("limit", String(limit));
    const url = `${BASE_API_URL}/items/itemOrder/unordered/search?${params.toString()}`;
    const res = await serverFetchJson<ItemOrderItem[]>(url, { method: "GET", next: { tags: ["itemOrder"] } });
    return res ?? [];
  },
);

export const saveItemOrder = async (orderedItemIds: number[]) => {
  const res = await serverFetchJson<any>(`${BASE_API_URL}/items/itemOrder/save`, {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ orderedItemIds }),
  });
  revalidateTag("itemOrder");
  return res;
};

