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

export interface StockAdjustmentLineRequest {
  id: number;
  lotNo?: string | null;
  adjustedQty: number;
  productlotNo?: string | null;
  dnNo?: string | null;
  isOpeningInventory: boolean;
  isNew: boolean;
  itemId: number;
  itemNo: string;
  expiryDate: string;
  warehouseId: number;
  uom?: string | null;
}

export interface StockAdjustmentRequest {
  itemId: number;
  originalLines: StockAdjustmentLineRequest[];
  currentLines: StockAdjustmentLineRequest[];
}

export interface MessageResponse {
  id: number | null;
  name: string;
  code: string;
  type: string;
  message: string | null;
  errorPosition: string | null;
}

export const submitStockAdjustment = async (data: StockAdjustmentRequest) => {
  const result = await serverFetchJson<MessageResponse>(
    `${BASE_API_URL}/stockAdjustment/submit`,
    {
      method: "POST",
      body: JSON.stringify(data),
      headers: { "Content-Type": "application/json" },
    },
  );
  revalidateTag("inventoryLotLines");
  revalidateTag("inventories");
  return result;
};