import { servicesConfig } from "$config/index.js";
import { sepahVerificationHelpers } from "$helpers/index.js";
import { isSepahBrokerFund } from "$services/sepah/sepah-broker.helper.js";

const ensureSepahVerified = 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.isSepahVerified === true) {
      return next();
    }

    const result = await sepahVerificationHelpers.syncUserSepahVerification(
      req.user,
      {
        throwOnLookupFailure: true,
      },
    );

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

    return res.status(403).send({
      message:
        "جهت ثبت نام در کارگزاری سپه میبایست از طریق لینک زیر ثبت نام نمایید",
      code: "SEPAH_VERIFICATION_REQUIRED",
      registerUrl: servicesConfig.sepahBrokerConfig.registerUrl,
    });
  } catch (error) {
    return res.status(error?.status || 503).send({
      message:
        error?.message || "بررسی وضعیت ثبت نام کارگزاری سپه انجام نشد.",
      code: error?.code || "SEPAH_VERIFICATION_FAILED",
      registerUrl: servicesConfig.sepahBrokerConfig.registerUrl,
    });
  }
};

export default ensureSepahVerified;
