"use server";
// import { BASE_API_URL } from "@/config/api";
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 { PoResult, StockInLine } from ".";
//import { serverFetchJson } from "@/app/utils/fetchUtil";
import { serverFetchJson, serverFetchWithNoContent } from "../../utils/fetchUtil";
import { QcItemResult } from "../settings/qcItem";
import { RecordsRes } from "../utils";
import { Uom } from "../settings/uom";
import { convertObjToURLSearchParams } from "@/app/utils/commonUtil";
// import { BASE_API_URL } from "@/config/api";
import { Result } from "../settings/item";

export interface PostStockInLineResponse<T> {
  id: number | null;
  name: string;
  code: string;
  type?: string;
  message: string | null;
  errorPosition: string | keyof T;
  entity: T | T[];
  // entity: StockInLine | StockInLine[]
}

export interface StockInLineEntry {
  id?: number;
  itemId: number;
  acceptedQty: number;
  purchaseOrderId?: number;
  purchaseOrderLineId?: number;
  jobOrderId?: number;
  status?: string;
  expiryDate?: string;
  productLotNo?: string;
  receiptDate?: string;
  dnDate?: string;
  dnNo?: string;
}

export interface QcResult{
  id?: number;
  qcItemId: number;
  qcPassed?: boolean;
  failQty?: number;
  remarks?: string;
  escalationLogId?: number;
}
export interface StockInInput {
  status: string;
  poCode: string;
  productLotNo?: string;
  dnNo?: string;
  dnDate?: string;
  itemName: string;
  lotNo?: string;
  invoiceNo?: string;
  receiptDate: string;
  supplier: string;
  acceptedQty: number;
  qty: number;
  receivedQty: number;
  acceptedWeight?: number;
  productionDate?: string;
  expiryDate: string;
  uom: Uom;
}
export interface QCInput {
  status: string;
  acceptQty: number;
  passingQty: number;
  sampleRate?: number;
  sampleWeight?: number;
  totalWeight?: number;
  qcAccept: boolean;
  qcDecision?: number;
  qcResult: QcResult[];
}
export interface EscalationInput {
  status: string;
  remarks?: string;
  reason?: string;
  handlerId: number;
  productLotNo?: string;
  acceptedQty?: number; // this is the qty to be escalated
  // escalationQty: number
}
export interface PutAwayLine {
  id?: number
  qty: number
  warehouseId: number;
  warehouse: string;
  printQty: number;
  _isNew?: boolean;
}
export interface PutAwayInput {
  status: string;
  acceptedQty: number;
  warehouseId: number;
  putAwayLines: PutAwayLine[]
}

export type ModalFormInput = Partial<
  QCInput & StockInInput & PutAwayInput
> & {
  escalationLog? : Partial<EscalationInput>
};

export interface PrintQrCodeForSilRequest {
  stockInLineId: number;
  printerId: number;
  printQty?: number;
}

export const testFetch = cache(async (id: number) => {
  return serverFetchJson<PoResult>(`${BASE_API_URL}/po/detail/${id}`, {
    next: { tags: ["po"] },
  });
});

export const fetchStockInLineInfo = cache(async (stockInLineId: number) => {
  return serverFetchJson<StockInLine>(
    `${BASE_API_URL}/stockInLine/${stockInLineId}`,
    {
      next: { tags: ["stockInLine"] },
    },
  );
});

export const createStockInLine = async (data: StockInLineEntry) => {
  const stockInLine = await serverFetchJson<
    PostStockInLineResponse<StockInLine>
  >(`${BASE_API_URL}/stockInLine/create`, {
    method: "POST",
    body: JSON.stringify(data),
    headers: { "Content-Type": "application/json" },
  });
  // revalidateTag("po");
  return stockInLine;
};

export const updateStockInLine = async (
  data: StockInLineEntry & ModalFormInput,
) => {
  const stockInLine = await serverFetchJson<
    PostStockInLineResponse<StockInLine & ModalFormInput>
  >(`${BASE_API_URL}/stockInLine/update`, {
    method: "POST",
    body: JSON.stringify(data),
    headers: { "Content-Type": "application/json" },
  });
  // revalidateTag("po");
  return stockInLine;
};

export const startPo = async (poId: number) => {
  const po = await serverFetchJson<PostStockInLineResponse<PoResult>>(
    `${BASE_API_URL}/po/start/${poId}`,
    {
      method: "POST",
      body: JSON.stringify({ poId }),
      headers: { "Content-Type": "application/json" },
    },
  );
  revalidateTag("po");
  return po;
};

export const checkPolAndCompletePo = async (poId: number) => {
  const po = await serverFetchJson<PostStockInLineResponse<PoResult>>(
    `${BASE_API_URL}/po/check/${poId}`,
    {
      method: "POST",
      body: JSON.stringify({ poId }),
      headers: { "Content-Type": "application/json" },
    },
  );
  revalidateTag("po");
  return po;
};

export const fetchPoInClient = cache(async (id: number) => {
  return serverFetchJson<PoResult>(`${BASE_API_URL}/po/detail/${id}`, {
    next: { tags: ["po"] },
  });
});

export const fetchPoListClient = cache(
  async (queryParams?: Record<string, any>) => {
    if (queryParams) {
      const queryString = new URLSearchParams(queryParams).toString();
      return serverFetchJson<RecordsRes<PoResult[]>>(
        `${BASE_API_URL}/po/list?${queryString}`,
        {
          method: "GET",
          next: { tags: ["po"] },
        },
      );
    } else {
      return serverFetchJson<RecordsRes<PoResult[]>>(
        `${BASE_API_URL}/po/list`,
        {
          method: "GET",
          next: { tags: ["po"] },
        },
      );
    }
  },
);

export const testing = cache(async (queryParams?: Record<string, any>) => {
  if (queryParams) {
    const queryString = new URLSearchParams(queryParams).toString();
    return serverFetchJson<RecordsRes<PoResult[]>>(
      `${BASE_API_URL}/po/testing?${queryString}`,
      {
        method: "GET",
        next: { tags: ["po"] },
      },
    );
  } else {
    return serverFetchJson<RecordsRes<PoResult[]>>(
      `${BASE_API_URL}/po/testing`,
      {
        method: "GET",
        next: { tags: ["po"] },
      },
    );
  }
});

export const printQrCodeForSil = cache(async(data: PrintQrCodeForSilRequest) => {
  const params = convertObjToURLSearchParams(data)
  return serverFetchWithNoContent(`${BASE_API_URL}/stockInLine/print-label?${params}`,
    {
      method: "GET",
      headers: { "Content-Type": "application/json" },
      next: {
        tags: ["printQrCodeForSil"],
      },
    },
  )
})
// 添加服务器端 action 用于从客户端组件获取 item 信息
export const fetchItemForPutAway = cache(async (id: number): Promise<Result> => {
  return serverFetchJson<Result>(`${BASE_API_URL}/items/details/${id}`, {
    next: { tags: ["items"] },
  });
});
