var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
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 __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var dingtalk_auth_exports = {};
__export(dingtalk_auth_exports, {
  DingtalkAuth: () => DingtalkAuth
});
module.exports = __toCommonJS(dingtalk_auth_exports);
var import_server = require("@tego/server");
var import_constants = require("../constants");
var import_dingtalk_client = require("./dingtalk-client");
class DingtalkAuth extends import_server.BaseAuth {
  constructor(config) {
    const { ctx } = config;
    super({
      ...config,
      userCollection: ctx.db.getCollection("users"),
      userStatusCollection: ctx.db.getCollection("userStatuses")
    });
  }
  async validate() {
    var _a, _b, _c, _d;
    const ctx = this.ctx;
    const { authCode } = ctx.action.params || {};
    if (!authCode) {
      ctx.throw(401, ctx.t("Please enter the authCode", { ns: import_constants.namespace }));
    }
    const dingtalkClient = new import_dingtalk_client.DingtalkClient({
      clientId: (_b = (_a = this.options) == null ? void 0 : _a.dingtalk) == null ? void 0 : _b.clientId,
      clientSecret: (_c = this.options) == null ? void 0 : _c.clientSecret
    });
    const accessToken = await dingtalkClient.getAccessToken(authCode);
    if (!accessToken) {
      ctx.throw(401, ctx.t("Failed to get accessToken", { ns: import_constants.namespace }));
    }
    const userInfo = await dingtalkClient.getUserInfo(accessToken);
    const { mobile, nick, email } = userInfo;
    if (!mobile) {
      ctx.throw(401, ctx.t("Failed to get mobile", { ns: import_constants.namespace }));
    }
    const authenticator = this.authenticator;
    let user = await authenticator.findUser(mobile);
    if (user) {
      return user;
    }
    user = await this.userRepository.findOne({
      filter: { phone: mobile }
    });
    if (user) {
      await authenticator.addUser(user.id, {
        through: {
          uuid: mobile
        }
      });
      return user;
    }
    const { autoSignup } = ((_d = this.options) == null ? void 0 : _d.public) || {};
    if (!autoSignup) {
      ctx.throw(401, ctx.t("User not found", { ns: import_constants.namespace }));
    }
    return await authenticator.newUser(mobile, {
      nickname: nick ?? null,
      phone: mobile ?? null,
      email: email ?? null
    });
  }
  async getAuthUrl(redirect) {
    var _a, _b;
    const clientId = (_b = (_a = this.options) == null ? void 0 : _a.dingtalk) == null ? void 0 : _b.clientId;
    const app = this.ctx.tego.name;
    const redirectUrl = encodeURIComponent(
      `${this.ctx.protocol}://${this.ctx.host}${process.env.API_BASE_PATH}dingtalk:redirect`
    );
    const state = encodeURIComponent(`redirect=${redirect}&app=${app}&name=${this.ctx.headers["x-authenticator"]}`);
    const url = `https://login.dingtalk.com/oauth2/auth?client_id=${clientId}&response_type=code&scope=openid&state=${state}&redirect_uri=${redirectUrl}&prompt=consent`;
    return url;
  }
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  DingtalkAuth
});
