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 verifications_exports = {};
__export(verifications_exports, {
  create: () => create
});
module.exports = __toCommonJS(verifications_exports);
var import_node_crypto = require("node:crypto");
var import_node_util = require("node:util");
var import_server = require("@tego/server");
var import_dayjs = __toESM(require("dayjs"));
var import__ = require("..");
var import_constants = require("../constants");
const asyncRandomInt = (0, import_node_util.promisify)(import_node_crypto.randomInt);
async function create(ctx, next) {
  const plugin = ctx.tego.pm.get("otp");
  const { values } = ctx.action.params;
  const interceptor = plugin.interceptors.get(values == null ? void 0 : values.type);
  if (!interceptor) {
    return ctx.throw(400, "Invalid action type");
  }
  const providerItem = await plugin.getDefault();
  if (!providerItem) {
    console.error(`[otp] no provider for action (${values.type}) provided`);
    return ctx.throw(500);
  }
  const receiver = interceptor.getReceiver(ctx);
  if (!receiver) {
    return ctx.throw(400, {
      code: "InvalidReceiver",
      message: ctx.t("Not a valid cellphone number, please re-enter", { ns: import__.namespace })
    });
  }
  const VerificationModel = ctx.db.getModel("verifications");
  const record = await VerificationModel.findOne({
    where: {
      type: values.type,
      receiver,
      status: import_constants.CODE_STATUS_UNUSED,
      expiresAt: {
        [import_server.Op.gt]: /* @__PURE__ */ new Date()
      }
    }
  });
  if (record) {
    const seconds = (0, import_dayjs.default)(record.get("expiresAt")).diff((0, import_dayjs.default)(), "seconds");
    return ctx.throw(429, {
      code: "RateLimit",
      message: ctx.t("Please don't retry in {{time}} seconds", { time: seconds, ns: import__.namespace })
    });
  }
  const code = (await asyncRandomInt(999999)).toString(10).padStart(6, "0");
  if (interceptor.validate) {
    try {
      await interceptor.validate(ctx, receiver);
    } catch (err) {
      return ctx.throw(400, { code: "InvalidReceiver", message: err.message });
    }
  }
  const ProviderType = plugin.providers.get(providerItem.get("type"));
  const provider = new ProviderType(plugin, providerItem.get("options"));
  try {
    await provider.send(receiver, { code });
    console.log("verification code sent");
  } catch (error) {
    switch (error.name) {
      case "InvalidReceiver":
        return ctx.throw(400, {
          code: "InvalidReceiver",
          message: ctx.t("Not a valid cellphone number, please re-enter", { ns: import__.namespace })
        });
      case "RateLimit":
        return ctx.throw(429, ctx.t("You are trying so frequently, please slow down", { ns: import__.namespace }));
      default:
        console.error(error);
        return ctx.throw(
          500,
          ctx.t("Verification send failed, please try later or contact to administrator", { ns: import__.namespace })
        );
    }
  }
  const data = {
    id: (0, import_node_crypto.randomUUID)(),
    type: values.type,
    receiver,
    content: code,
    expiresAt: Date.now() + (interceptor.expiresIn ?? 60) * 1e3,
    status: import_constants.CODE_STATUS_UNUSED,
    providerId: providerItem.get("id")
  };
  ctx.action.mergeParams(
    {
      values: data
    },
    {
      values: "overwrite"
    }
  );
  await import_server.actions.create(ctx, async () => {
    const { body: result } = ctx;
    ctx.body = {
      id: result.id,
      expiresAt: result.expiresAt
    };
    return next();
  });
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  create
});
