import { Api } from "./api";
import { Response } from "../redux/Common/types";
import { ReorderShopifyStoreRequest } from "models/talent/talent-profile-module.model";
import Client from "shopify-buy";
export default class ShopifyServices {
  constructor(private readonly api: Api) {
    this.api = api;
  }

  getAuthUrl = (storeDomain: string): Promise<Response<any>> => {
    return this.api.getAuthShopifyUrl(storeDomain);
  };

  updateStoreName = (
    storeDomain: string,
    name: string
  ): Promise<Response<any>> => {
    return this.api.updateShopifyStoreName(storeDomain, name);
  };

  updateStoreStatus = (
    storeDomain: string,
    connected: boolean
  ): Promise<Response<any>> => {
    return this.api.updateShopifyStoreStatus(storeDomain, connected);
  };

  createClient = (accessToken: string, domain: string) => {
    const client = Client.buildClient({
      apiVersion: "2023-10",
      storefrontAccessToken: accessToken,
      domain: domain,
    });
    return client;
  };

  removeStore = (storeDomain: string): Promise<Response<any>> => {
    return this.api.removeShopifyStore(storeDomain);
  };

  reorderStore = (payload: ReorderShopifyStoreRequest[]) => {
    return this.api.reorderShopifyStore(payload);
  };

  async getAuthToken(): Promise<string> {
    return this.api.postRequest("rye/auth", {}).then((data) => {
      return (data as any)?.response?.result.token;
    });
  }

  async getRyeShopifyStores(talentProfileId: string): Promise<any> {
    return this.api.getRequest(`/rye/shopify/${talentProfileId}/shops`);
  }

  async reorderRyeShopifyStore(
    payload: ReorderShopifyStoreRequest[]
  ): Promise<any> {
    return this.api.putRequest(`/rye/shopify/token/re-order`, payload);
  }

  async createRyeShopifyStore(
    talentProfileId: string,
    storeDomain: string
  ): Promise<any> {
    return this.api.postRequest(
      `/rye/shopify/${talentProfileId}/${encodeURI(storeDomain)}`,
      {
        talent_profile_id: talentProfileId,
        store: storeDomain,
      }
    );
  }

  async updateRyeShopifyStoreStatus(
    talentProfileId: string,
    storeDomain: string,
    connected: boolean
  ): Promise<any> {
    return this.api.patchRequest(
      `/rye/shopify/${talentProfileId}/${encodeURI(storeDomain)}`,
      {
        connected,
      }
    );
  }

  async updateRyeShopifyStoreName(
    talentProfileId: string,
    storeDomain: string,
    name: string
  ): Promise<any> {
    return this.api.patchRequest(
      `/rye/shopify/${talentProfileId}/${encodeURI(storeDomain)}`,
      {
        name,
      }
    );
  }

  async removeRyeShopifyStore(
    talentProfileId: string,
    storeDomain: string
  ): Promise<any> {
    return this.api.deleteRequest(
      `/rye/shopify/${talentProfileId}/${encodeURI(storeDomain)}`
    );
  }
}
