"use strict";
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
  // If the importer is in node compatibility mode or this is not an ESM
  // file that has been converted to a CommonJS file using a Babel-
  // compatible transform (i.e. "__esModule" has not been set), then set
  // "default" to the CommonJS "module.exports" for node compatibility.
  isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
  mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var use_ai_request_service_exports = {};
__export(use_ai_request_service_exports, {
  useAiRequestService: () => useAiRequestService
});
module.exports = __toCommonJS(use_ai_request_service_exports);
var import_lodash = __toESM(require("lodash"));
var import_react = __toESM(require("react"));
var import_ricos_context = require("./../../ricos-context/index.js");
var import_request_service_provider = require("./../../_shared/request-service-provider/request-service-provider.js");
const API_ENDPOINT = "https://www.wix-pages.com/_serverless/ricos-ai-gateway";
const pluckErrorMessage = (error, fallback) => import_lodash.default.isObject(error) && "message" in error && import_lodash.default.isString(error.message) ? error.message : fallback;
const useAiRequestService = (config) => {
  const { t } = (0, import_react.useContext)(import_ricos_context.RicosContext);
  const { makeRequest } = (0, import_request_service_provider.useRequestService)();
  const devAiRequestService = (0, import_ricos_context.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 import_react.default.useMemo(() => {
    return {
      fetchPrompt,
      fetchImagePrompt,
      fetchPromptFromSelection
    };
  }, [makeRequest]);
};
//# sourceMappingURL=use-ai-request-service.js.map
