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

// src/components/authentication/admin/OAuthConfig/index.tsx
var OAuthConfig_exports = {};
__export(OAuthConfig_exports, {
  default: () => OAuthConfig_default
});
module.exports = __toCommonJS(OAuthConfig_exports);
var import_react = __toESM(require("react"));
var import_antd = require("antd");
var import_utils = require("@pisell/utils");
var import_icons = require("@ant-design/icons");
var import_types = require("../AuthMethods/types");
var import_SettingList = __toESM(require("../AuthMethods/SettingList"));
var import_useEngineContext = __toESM(require("../../../../hooks/useEngineContext"));
var import_locales = __toESM(require("./locales"));
var import_OAuthConfig = require("./OAuthConfig.less");
var { Title, Paragraph } = import_antd.Typography;
var OAuthConfig = ({ className, style, onSave }) => {
  var _a, _b;
  const context = (0, import_useEngineContext.default)();
  const app = context.appHelper.utils.getApp();
  const { request, data } = context.appHelper.utils.getApp();
  import_utils.locales.init(import_locales.default, ((_b = (_a = context == null ? void 0 : context.engine) == null ? void 0 : _a.props) == null ? void 0 : _b.locale) || "en");
  const [form] = import_antd.Form.useForm();
  const [drawerOpen, setDrawerOpen] = (0, import_react.useState)(false);
  const [currentProvider, setCurrentProvider] = (0, import_react.useState)(null);
  const [tenantId, setTenantId] = (0, import_react.useState)(null);
  (0, import_react.useEffect)(() => {
    console.log("app_init_oauth_config", app, context, data.storage);
  }, []);
  (0, import_react.useEffect)(() => {
    var _a2;
    const coreData = data.storage.getStorage("core");
    if (coreData) {
      try {
        const coreDataJson = JSON.parse(coreData);
        if ((_a2 = coreDataJson == null ? void 0 : coreDataJson.tenant) == null ? void 0 : _a2.id) {
          setTenantId(coreDataJson.tenant.id);
        }
      } catch (error) {
        console.error("Error parsing core data:", error);
      }
    }
  }, [data.storage]);
  const providers = (0, import_react.useMemo)(() => {
    return [
      // 暂时注释 google
      // {
      //   id: 'google',
      //   name: locales.getText('oauth.provider.google'),
      //   description: locales.getText('oauth.provider.google.description'),
      //   icon: <GoogleOutlined style={{ fontSize: 24, color: '#4285F4' }} />,
      //   configured: false,
      // },
      {
        id: "apple",
        name: import_utils.locales.getText("oauth.provider.apple"),
        description: import_utils.locales.getText("oauth.provider.apple.description"),
        icon: /* @__PURE__ */ import_react.default.createElement(import_icons.AppleOutlined, { style: { fontSize: 24, color: "#000000" } }),
        configured: false
      },
      {
        id: "facebook",
        name: import_utils.locales.getText("oauth.provider.facebook"),
        description: import_utils.locales.getText("oauth.provider.facebook.description"),
        icon: /* @__PURE__ */ import_react.default.createElement(import_icons.FacebookOutlined, { style: { fontSize: 24, color: "#1877F2" } }),
        configured: false
      }
    ];
  }, []);
  const authMethods = (0, import_react.useMemo)(() => {
    return providers.map((provider) => ({
      id: provider.id,
      type: provider.id.toUpperCase(),
      title: provider.name,
      category: import_types.AuthMethodCategory.OAUTH,
      description: provider.description,
      icon: provider.icon,
      enabled: provider.configured,
      hasSettings: true
    }));
  }, [providers]);
  const fetchProviderData = async (providerId) => {
    var _a2, _b2;
    if (!tenantId) return;
    const dataKey = `auth.oauth.${providerId}`;
    try {
      const res = await request.get(`/tenant/core/meta?key=${dataKey}&metable_type=tenant&metable_id=${tenantId}`);
      console.log(`res_oauth_${providerId}_data`, res);
      if ((_a2 = res == null ? void 0 : res.data) == null ? void 0 : _a2.length) {
        const configData = (_b2 = res.data[0]) == null ? void 0 : _b2.value;
        console.log(`${providerId} config data:`, configData);
        if (providerId === "facebook") {
          form.setFieldsValue({
            appid: configData.appid || "",
            secret_key: configData.secret_key || ""
          });
        } else if (providerId === "apple") {
          form.setFieldsValue({
            identifier: configData.identifier || ""
          });
        }
      }
    } catch (error) {
      console.error(`Error fetching ${providerId} data:`, error);
    }
  };
  const handleSettings = (method) => {
    const provider = providers.find((p) => p.id === method.id);
    if (provider) {
      setCurrentProvider(provider);
      setDrawerOpen(true);
      fetchProviderData(provider.id);
    }
  };
  const handleDrawerClose = () => {
    setDrawerOpen(false);
    setCurrentProvider(null);
    form.resetFields();
  };
  const handleSaveSettings = async () => {
    if (!currentProvider || !tenantId) return;
    try {
      const values = await form.validateFields();
      console.log("Saving settings:", values);
      const dataKey = `auth.oauth.${currentProvider.id}`;
      let configData = {};
      if (currentProvider.id === "facebook") {
        configData = {
          appid: values.appid,
          secret_key: values.secret_key
        };
      } else if (currentProvider.id === "apple") {
        configData = {
          identifier: values.identifier
        };
      }
      console.log("Saving to API:", { dataKey, configData });
      await request.post(`/tenant/core/meta/tenant/${tenantId}`, {
        [dataKey]: configData
      });
      import_antd.message.success(import_utils.locales.getText("oauth.save.success") || "保存成功");
      handleDrawerClose();
    } catch (error) {
      console.error("Validation failed or save error:", error);
      import_antd.message.error(import_utils.locales.getText("oauth.save.error") || "保存失败");
    }
  };
  return /* @__PURE__ */ import_react.default.createElement("div", { className: `oauth-config ${className || ""}`, style }, /* @__PURE__ */ import_react.default.createElement("div", { className: "oauth-config-header" }, /* @__PURE__ */ import_react.default.createElement(Title, { level: 1, className: "oauth-config-title" }, import_utils.locales.getText("oauth.config.title")), /* @__PURE__ */ import_react.default.createElement(Paragraph, { className: "oauth-config-description" }, import_utils.locales.getText("oauth.config.description"))), /* @__PURE__ */ import_react.default.createElement("div", { className: "oauth-config-section" }, /* @__PURE__ */ import_react.default.createElement("div", { className: "oauth-config-section-layout" }, /* @__PURE__ */ import_react.default.createElement("div", { className: "oauth-config-section-header" }, /* @__PURE__ */ import_react.default.createElement(Title, { level: 2, className: "oauth-config-section-title" }, import_utils.locales.getText("oauth.providers.title")), /* @__PURE__ */ import_react.default.createElement(Paragraph, { className: "oauth-config-section-description" }, import_utils.locales.getText("oauth.providers.description"))), /* @__PURE__ */ import_react.default.createElement("div", { className: "oauth-config-section-content" }, /* @__PURE__ */ import_react.default.createElement(
    import_SettingList.default,
    {
      methods: authMethods,
      onSettings: handleSettings,
      enableSetting: true
    }
  )))), /* @__PURE__ */ import_react.default.createElement(
    import_antd.Drawer,
    {
      title: currentProvider ? `${currentProvider.name} ${import_utils.locales.getText("oauth.drawer.title")}` : "",
      placement: "right",
      width: 500,
      open: drawerOpen,
      onClose: handleDrawerClose
    },
    /* @__PURE__ */ import_react.default.createElement("div", { style: { display: "flex", flexDirection: "column", height: "100%" } }, /* @__PURE__ */ import_react.default.createElement("div", { style: { flex: 1 } }, (currentProvider == null ? void 0 : currentProvider.id) === "apple" && /* @__PURE__ */ import_react.default.createElement(import_antd.Form, { form, layout: "vertical" }, /* @__PURE__ */ import_react.default.createElement(
      import_antd.Form.Item,
      {
        label: import_utils.locales.getText("oauth.apple.identifier"),
        name: "identifier",
        rules: [{ required: true, message: import_utils.locales.getText("oauth.apple.identifier.required") }]
      },
      /* @__PURE__ */ import_react.default.createElement(import_antd.Input, { placeholder: import_utils.locales.getText("oauth.apple.identifier.placeholder") })
    )), (currentProvider == null ? void 0 : currentProvider.id) === "facebook" && /* @__PURE__ */ import_react.default.createElement(import_antd.Form, { form, layout: "vertical" }, /* @__PURE__ */ import_react.default.createElement(
      import_antd.Form.Item,
      {
        label: import_utils.locales.getText("oauth.facebook.appId"),
        name: "appid",
        rules: [{ required: true, message: import_utils.locales.getText("oauth.facebook.appId.required") }]
      },
      /* @__PURE__ */ import_react.default.createElement(import_antd.Input, { placeholder: import_utils.locales.getText("oauth.facebook.appId.placeholder") })
    ), /* @__PURE__ */ import_react.default.createElement(
      import_antd.Form.Item,
      {
        label: import_utils.locales.getText("oauth.facebook.appSecret"),
        name: "secret_key",
        rules: [{ required: true, message: import_utils.locales.getText("oauth.facebook.appSecret.required") }]
      },
      /* @__PURE__ */ import_react.default.createElement(import_antd.Input.Password, { placeholder: import_utils.locales.getText("oauth.facebook.appSecret.placeholder") })
    ))), /* @__PURE__ */ import_react.default.createElement("div", { style: {
      display: "flex",
      gap: "8px",
      justifyContent: "flex-end",
      padding: "16px 0",
      borderTop: "1px solid #f0f0f0",
      marginTop: "auto"
    } }, /* @__PURE__ */ import_react.default.createElement(import_antd.Button, { onClick: handleDrawerClose }, import_utils.locales.getText("oauth.button.cancel")), /* @__PURE__ */ import_react.default.createElement(import_antd.Button, { type: "primary", onClick: handleSaveSettings }, import_utils.locales.getText("oauth.button.save"))))
  ));
};
var OAuthConfig_default = OAuthConfig;
