import lodash from "lodash";
import React, { useContext } from "react";
import { RicosContext, useDevAiRequestService } from "./../../ricos-context/index.js";
import { useRequestService } from "./../../_shared/request-service-provider/request-service-provider.js";
const API_ENDPOINT = "https://www.wix-pages.com/_serverless/ricos-ai-gateway";
const pluckErrorMessage = (error, fallback) => lodash.isObject(error) && "message" in error && lodash.isString(error.message) ? error.message : fallback;
const useAiRequestService = (config) => {
  const { t } = useContext(RicosContext);
  const { makeRequest } = useRequestService();
  const devAiRequestService = useDevAiRequestService();
  if (devAiRequestService) {
    return devAiRequestService;
  }
  const gatewayBaseUrl = config.getGatewayBaseUrl ? config.getGatewayBaseUrl() : API_ENDPOINT;
  const appDefId = config.appDefId;
  const fetchPrompt = async (prompt, content) => {
    try {
      const response = await makeRequest(`${gatewayBaseUrl}/prompt`, {
        method: "POST",
        headers: {
          "Content-Type": "application/json"
        },
        body: JSON.stringify({
          ...prompt,
          content,
          appDefId
        })
      });
      const results = await response.json();
      return { type: "SUCCESS", results };
    } catch (error) {
      return { type: "ERROR", error: pluckErrorMessage(error, "") };
    }
  };
  const fetchImagePrompt = async (body) => {
    try {
      const baseUrl = typeof location !== "undefined" && location.hostname === "editor.wix.com" ? "https://editor.wix.com/_api/ricos-ai-images/v1/ai-images" : "https://www.wixapis.com/ricos/v1/ai-images";
      const response = await makeRequest(`${baseUrl}/generate`, {
        method: "POST",
        headers: {
          "Content-Type": "application/json"
        },
        body: JSON.stringify({
          prompt: body.prompt,
          style: body.imageStyle || "NONE"
        })
      });
      if (!response.ok) {
        const errorData = await response.json().catch(() => ({}));
        if (errorData.details?.applicationError?.code === "CONTENT_VALIDATION_FAILED") {
          return {
            type: "VALIDATION_ERROR",
            error: t("AIPlugin_Error_Content_Validation_Text")
          };
        }
        if (response.status === 429) {
          return {
            type: "RATE_LIMIT_ERROR",
            error: t("AIPlugin_Error_Rate_Limit_Text")
          };
        }
        throw new Error(errorData.message || `HTTP ${response.status}: ${response.statusText}`);
      }
      const responseData = await response.json();
      const url = responseData.image.url;
      const blob = await fetch(url).then((response2) => response2.blob());
      const results = { url: window.URL.createObjectURL(blob), blob };
      return { type: "SUCCESS", results };
    } catch (error) {
      if (error instanceof TypeError && error.message === "Failed to fetch") {
        return {
          type: "RATE_LIMIT_ERROR",
          error: t("AIPlugin_Error_Rate_Limit_Text")
        };
      }
      return { type: "ERROR", error: pluckErrorMessage(error, "") };
    }
  };
  const fetchPromptFromSelection = async (body) => {
    try {
      const response = await makeRequest(`${gatewayBaseUrl}/convert-text-to-prompt`, {
        method: "POST",
        headers: {
          "Content-Type": "application/json"
        },
        body: JSON.stringify({
          selectedText: body.selection,
          appDefId
        })
      });
      const results = await response.json();
      return { type: "SUCCESS", results };
    } catch (error) {
      return { type: "ERROR", error: pluckErrorMessage(error, "") };
    }
  };
  return React.useMemo(() => {
    return {
      fetchPrompt,
      fetchImagePrompt,
      fetchPromptFromSelection
    };
  }, [makeRequest]);
};
export {
  useAiRequestService
};
//# sourceMappingURL=use-ai-request-service.js.map
