import { tadbirServices } from "$services/index.js";
import { isSepahBrokerFund } from "$services/sepah/sepah-broker.helper.js";

const ensureTadbirVerified = async (req, res, next) => {
  try {
    if (!req.user?._id) {
      return res.status(401).send({ message: "Unauthorized" });
    }

    const fundRegisterCode = String(
      req.params?.fundId ||
        req.body?.fundId ||
        req.body?.fundRegisterCode ||
        req.body?.fundSeoRegisterNo ||
        "",
    ).trim();

    if (isSepahBrokerFund(fundRegisterCode)) {
      return next();
    }

    if (req.user.isTadbirVerified === true) {
      return next();
    }

    await tadbirServices.tadbirCreateUser(req.user);
    req.user.isTadbirVerified = true;
    return next();
  } catch (error) {
    return res.status(error?.status || 422).send({
      message: error?.message || "ثبت کاربر در تدبیر ناموفق بود.",
      code: error?.code || "TADBIR_VERIFICATION_FAILED",
    });
  }
};

export default ensureTadbirVerified;
