"use server";

import { serverFetchString, serverFetchWithNoContent, serverFetchJson } from "@/app/utils/fetchUtil";
import { BASE_API_URL } from "@/config/api";
import { revalidateTag } from "next/cache";
import { WarehouseResult, StockTakeSectionInfo } from "./index";
import { cache } from "react";

export interface WarehouseInputs {
  code?: string;
  name?: string;
  description?: string;
  capacity?: number;
  store_id?: string;
  warehouse?: string;
  area?: string;
  slot?: string;
  order?: string;
  stockTakeSection?: string;
  stockTakeSectionDescription?: string;
}

export const fetchWarehouseDetail = cache(async (id: number) => {
  return serverFetchJson<WarehouseResult>(`${BASE_API_URL}/warehouse/${id}`, {
    next: { tags: ["warehouse"] },
  });
});

export const createWarehouse = async (data: WarehouseInputs) => {
  const newWarehouse = await serverFetchWithNoContent(`${BASE_API_URL}/warehouse/save`, {
    method: "POST",
    body: JSON.stringify(data),
    headers: { "Content-Type": "application/json" },
  });
  revalidateTag("warehouse");
  return newWarehouse;
};

export const editWarehouse = async (id: number, data: WarehouseInputs) => {
  // Backend uses the same /warehouse/save POST endpoint for both create and update,
  // distinguished by presence of id in the payload.
  const updatedWarehouse = await serverFetchWithNoContent(`${BASE_API_URL}/warehouse/save`, {
    method: "POST",
    body: JSON.stringify({ id, ...data }),
    headers: { "Content-Type": "application/json" },
  });
  revalidateTag("warehouse");
  return updatedWarehouse;
};

export const deleteWarehouse = async (id: number) => {
  try {
    const result = await serverFetchJson<WarehouseResult[]>(`${BASE_API_URL}/warehouse/${id}`, {
      method: "DELETE",
      headers: { "Content-Type": "application/json" },
    });
    revalidateTag("warehouse");
    return result;
  } catch (error) {
    console.error("Error deleting warehouse:", error);
    revalidateTag("warehouse");
    throw error;
  }
};

export const importWarehouse = async (data: FormData) => {
    const importWarehouse = await serverFetchString<string>(
        `${BASE_API_URL}/warehouse/import`,
        {
            method: "POST",
            body: data,
        },
    );
    return importWarehouse;
}
export const importNewWarehouse = async (data: FormData) => {
    const importWarehouse = await serverFetchString<string>(
        `${BASE_API_URL}/warehouse/importNew`,
        {
            method: "POST",
            body: data,
        },
    );
    return importWarehouse;
}

export const fetchStockTakeSections = cache(async () => {
  return serverFetchJson<StockTakeSectionInfo[]>(`${BASE_API_URL}/warehouse/stockTakeSections`, {
    next: { tags: ["warehouse"] },
  });
});

export const updateSectionDescription = async (section: string, stockTakeSectionDescription: string | null) => {
  await serverFetchWithNoContent(
    `${BASE_API_URL}/warehouse/section/${encodeURIComponent(section)}/description`,
    {
      method: "PATCH",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ stockTakeSectionDescription }),
    }
  );
  revalidateTag("warehouse");
};

export const clearWarehouseSection = async (warehouseId: number) => {
  const result = await serverFetchJson<WarehouseResult>(
    `${BASE_API_URL}/warehouse/${warehouseId}/clearSection`,
    { method: "POST" }
  );
  revalidateTag("warehouse");
  return result;
};
export const getWarehousesBySection = cache(async (stockTakeSection: string) => {
  const list = await serverFetchJson<WarehouseResult[]>(`${BASE_API_URL}/warehouse`, {
    next: { tags: ["warehouse"] },
  });
  const items = Array.isArray(list) ? list : [];
  return items.filter((w) => w.stockTakeSection === stockTakeSection);
});
export const searchWarehousesForAddToSection = cache(async (
  params: { store_id?: string; warehouse?: string; area?: string; slot?: string },
  currentSection: string
) => {
  const list = await serverFetchJson<WarehouseResult[]>(`${BASE_API_URL}/warehouse`, {
    next: { tags: ["warehouse"] },
  });
  const items = Array.isArray(list) ? list : [];
  const storeId = params.store_id?.trim();
  const warehouse = params.warehouse?.trim();
  const area = params.area?.trim();
  const slot = params.slot?.trim();

  return items.filter((w) => {
    if (w.stockTakeSection != null && w.stockTakeSection !== currentSection) return false;
    if (!w.code) return true;
    const parts = w.code.split("-");
    if (storeId && parts[0] !== storeId) return false;
    if (warehouse && parts[1] !== warehouse) return false;
    if (area && parts[2] !== area) return false;
    if (slot && parts[3] !== slot) return false;
    return true;
  });
});