"use server";
import { BASE_API_URL } from "@/config/api";
// import { ServerFetchError, serverFetchJson, serverFetchWithNoContent } from "@/app/utils/fetchUtil";
import { revalidateTag } from "next/cache";
import { cache } from "react";
import { Pageable, serverFetchJson } from "@/app/utils/fetchUtil";
import { QcItemResult } from "../settings/qcItem";
import { RecordsRes } from "../utils";
import { convertObjToURLSearchParams } from "@/app/utils/commonUtil";
import { InventoryLotLineResult, InventoryResult } from ".";

export type InventoryListRow = Pick<
  InventoryResult,
  "itemId" | "itemCode" | "itemName" | "itemType"
>;
// import { BASE_API_URL } from "@/config/api";

export interface LotLineInfo {
  inventoryLotLineId: number;
  itemId: number;
  itemNo: string;
  itemName: string;
  lotNo: string;
  remainingQty: number;
  uom: string;
}

export interface SearchInventoryLotLine extends Pageable {
  itemId: number;
  /** Non-expired lots with in > out; includes available and unavailable. */
  stockIssueBadItem?: boolean;
}

export interface SearchStockIssueBadItemLotLine extends Pageable {
  itemCode?: string;
  itemName?: string;
  itemType?: string;
  lotNo?: string;
}

export interface SearchInventory extends Pageable {
  code: string;
  name: string;
  type: string;
  lotNo?: string;
}

export interface InventoryResultByPage {
  total: number;
  records: InventoryResult[];
}
export interface UpdateInventoryLotLineStatusRequest {
  inventoryLotLineId: number;
  status: string;
}
export interface InventoryLotLineResultByPage {
  total: number;
  records: InventoryLotLineResult[];
}
export interface PostInventoryLotLineResponse<T = null> {
  id: number | null;
  name: string;
  code: string;
  type?: string;
  message: string | null;
  errorPosition: string
  entity?: T | T[];
  consoCode?: string;
}
export interface QrCodeAnalysisResponse {
  itemId: number;
  itemCode: string;
  itemName: string;
  scanned: ScannedLotInfo;
  sameItemLots: SameItemLotInfo[];
}
export interface ScannedLotInfo {
  stockInLineId: number;
  lotNo: string;
  inventoryLotLineId: number;
}
export interface SameItemLotInfo {
  lotNo: string;
  inventoryLotLineId: number;
  availableQty: number;
  uom: string;
}
/** FG / inventory label modal: same-item lots use in − out − hold. */
export const analyzeQrCode = async (data: { itemId: number; stockInLineId: number }) => {
  return serverFetchJson<QrCodeAnalysisResponse>(`${BASE_API_URL}/inventoryLotLine/analyze-qr-code`, {
    method: 'POST',
    body: JSON.stringify(data),
    headers: { "Content-Type": "application/json" },
  });
};

/** DO workbench label modal only: same-item lots use in − out (no hold). */
export const workbenchAnalyzeQrCode = async (data: { itemId: number; stockInLineId: number }) => {
  return serverFetchJson<QrCodeAnalysisResponse>(
    `${BASE_API_URL}/inventoryLotLine/workbench/analyze-qr-code`,
    {
      method: 'POST',
      body: JSON.stringify(data),
      headers: { "Content-Type": "application/json" },
    },
  );
};
export const updateInventoryStatus = async (data: {
  itemId: number;
  lotId: number;
  status: string;
  qty: number;
}) => {
  return serverFetchJson(`${BASE_API_URL}/inventory/update-status`, {
    method: 'PUT',
    body: JSON.stringify(data)
  });
};
export const fetchLotDetail = cache(async (stockInLineId: number) => {
  return serverFetchJson<LotLineInfo>(
    `${BASE_API_URL}/inventoryLotLine/lot-detail/${stockInLineId}`,
    {
      method: "GET",
      next: { tags: ["inventory"] },
    },
  );
});
export const updateInventoryLotLineStatus = async (data: {
  inventoryLotLineId: number;
  status: string;
}) => {
  const res = await serverFetchJson<PostInventoryLotLineResponse<InventoryLotLineResult>>(
    `${BASE_API_URL}/inventoryLotLine/updateStatus`,
    {
      next: { tags: ["inventoryLotLine"] },
      method: "POST",
      body: JSON.stringify(data),
      headers: { "Content-Type": "application/json" },
    },
  );
  if (res?.code === "SUCCESS") {
    revalidateTag("inventoryLotLines");
    revalidateTag("inventories");
  }
  return res;
};

/** Full inventory list (for item-type filter options). Not wrapped in cache(). */
export async function fetchInventoryListFresh() {
  return serverFetchJson<InventoryListRow[]>(`${BASE_API_URL}/inventory/list`, {
    next: { tags: ["inventories"] },
  });
}

async function fetchInventoriesImpl(data: SearchInventory) {
  const queryStr = convertObjToURLSearchParams(data);
  return serverFetchJson<InventoryResultByPage>(
    `${BASE_API_URL}/inventory/getRecordByPage?${queryStr}`,
    { next: { tags: ["inventories"] } },
  );
}

export const fetchInventories = cache(fetchInventoriesImpl);

/** Bypass React cache() after mutations so lists show fresh qty. */
export async function fetchInventoriesFresh(data: SearchInventory) {
  return fetchInventoriesImpl(data);
}

async function fetchInventoryLotLinesImpl(data: SearchInventoryLotLine) {
  const queryStr = convertObjToURLSearchParams(data);
  return serverFetchJson<InventoryLotLineResultByPage>(
    `${BASE_API_URL}/inventoryLotLine/getRecordByPage?${queryStr}`,
    { next: { tags: ["inventoryLotLines"] } },
  );
}

export const fetchInventoryLotLines = cache(fetchInventoryLotLinesImpl);

/** Bypass React cache() after mutations so lists show fresh qty. */
export async function fetchInventoryLotLinesFresh(data: SearchInventoryLotLine) {
  return fetchInventoryLotLinesImpl(data);
}

export async function fetchStockIssueBadItemLotLinesFresh(
  data: SearchStockIssueBadItemLotLine,
) {
  const queryStr = convertObjToURLSearchParams(data);
  return serverFetchJson<InventoryLotLineResultByPage>(
    `${BASE_API_URL}/inventoryLotLine/stockIssueBadItemSearch?${queryStr}`,
    { next: { tags: ["inventoryLotLines"] } },
  );
}
export const updateInventoryLotLineQuantities = async (data: {
  inventoryLotLineId: number;
  qty: number;
  operation: string;
  status: string;
}) => {
  const result = await serverFetchJson<any>(
    `${BASE_API_URL}/inventoryLotLine/updateQuantities`,
    {
      method: "POST",
      body: JSON.stringify(data),
      headers: { "Content-Type": "application/json" },
    },
  );
  revalidateTag("pickorder");
  return result;
};

//STOCK TRANSFER
export interface CreateStockTransferRequest {
  inventoryLotLineId: number;
  transferredQty: number;
  warehouseId: number;
}

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

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