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

class ProductApiService {
  item_per_page = 10;

  async index(filter?: {
    skip?: number;
    limit?: number;
    order?: string;
    where?: Record<string, any>;
    info?: any;
  }) {
    const defaultFilter = {
      skip: 0,
      limit: 10,
      order: "updatedAt desc",
      where: {
        account: "prology_net",
        status: "Updated",
      },
    };

    return axios({
      method: "POST",
      data: {
        urlAPI: "/api/ebay-listing/listing-get-list",
        filter: {
          ...defaultFilter,
          ...filter, // merge filter vào defaultFilter
          where: {
            ...defaultFilter.where,
            ...filter?.where, // merge where riêng để không mất account/status mặc định
          },
        },
      },
    });
  }

  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",
      },
    });
  }

  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() {
    return axios({
      url: "data",
    });
  }

  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();
