import axios from "@/lib/axios";
import type { IPost, ISyncItem } from "@/lib/utils";

class ProductApiService {
  item_per_page = 10;

  async index(params?: Record<string, any>) {
    return axios({
      method: "GET",
      url: "products",
      params,
    });
  }

  async get(data: IPost) {
    // return axios({
    //   method: "POST",
    //   data: {
    //     filter: {
    //       where: {
    //         account: "prology_net",
    //         condition: data.raw_condition,
    //         productModelCode: data.sku,
    //       },
    //     },
    //     pageCurrent: "/ebaytools/listing-ebay",
    //     urlAPI: "/api/ebay-listing/get-image-listing",
    //   },
    // });
    return axios({
      method: "GET",
      url: "products/" + data.ebayListingId,
    });
  }

  async publish(data: IPost) {
    return axios({
      method: "POST",
      url: "products/publish/" + data.ebayListingId,
      data: {
        info: (data as any).info || {},
        hash_info: (data as any).hash_info,
      },
    });
  }

  async unlist(data: IPost) {
    return axios({
      method: "POST",
      url: "products/unlist/" + data.ebayListingId,
      data: {
        info: (data as any).info || {},
        hash_info: (data as any).hash_info,
      },
    });
  }

  async getProductOnLocalServer(data: IPost) {
    return axios({
      method: "GET",
      url: "products/" + data.id,
    });
  }

  async saveProductOnLocalServer(data: IPost) {
    return axios({
      method: "POST",
      url: "products",
      data,
    });
  }

  async sync(data: ISyncItem[]) {
    return axios({
      url: "sync",
      method: "POST",
      data,
    });
  }

  async getPublistedProducts(info: string) {
    return axios({
      url: "data",
      params: { info },
    });
  }

  async apiRequest(
    fn:
      | "index"
      | "getPublistedProducts"
      | "get"
      | "createBlobUrl"
      | "publist"
      | "unlist"
      | "sync"
      | "dequeue"
      | "getProductLocalServer"
      | "saveProductLocalServer",
    body: Record<string, any>
  ) {
    return new Promise((resolve, reject) => {
      const requestId = "req_" + Date.now() + "_" + Math.random();

      // Lắng nghe 1 lần response cho requestId
      function handleResponse(event: any) {
        if (
          event.data.type === "API_RESPONSE" &&
          event.data.requestId === requestId
        ) {
          window.removeEventListener("message", handleResponse);

          if (event.data.error) {
            reject(event.data.error);
          } else {
            resolve(event.data.payload);
          }
        }
      }

      window.addEventListener("message", handleResponse);

      // Gửi yêu cầu
      window.postMessage(
        {
          type: "API_REQUEST",
          requestId,
          payload: body,
          fn,
        },
        "*"
      );
    });
  }
}

export const productApi = new ProductApiService();
