import { getUserIdentifier } from "$helpers/identity/identity.helper.js";
import models from "$models/index.js";
import { sepahBrokerServices } from "$services/index.js";

const extractPartyId = (payload = {}) => {
  const candidates = [
    payload?.PartyId,
    payload?.partyId,
    payload?.data?.PartyId,
    payload?.data?.partyId,
    payload?.result?.PartyId,
    payload?.result?.partyId,
  ];

  for (const candidate of candidates) {
    const parsedCandidate = Number(candidate);
    if (Number.isFinite(parsedCandidate) && parsedCandidate > 0) {
      return parsedCandidate;
    }
  }

  return null;
};

const extractMessage = (payload = {}) => {
  const candidates = [
    payload?.Message,
    payload?.message,
    payload?.data?.Message,
    payload?.data?.message,
    payload?.result?.Message,
    payload?.result?.message,
  ];

  for (const candidate of candidates) {
    if (candidate !== undefined && candidate !== null && candidate !== "") {
      return String(candidate).trim();
    }
  }

  return "";
};

export const resolveSepahCustomerStatus = (payload = {}) => {
  const partyId = extractPartyId(payload);

  return {
    isSepahVerified: Boolean(partyId),
    partyId,
    message: extractMessage(payload),
    payload,
  };
};

export const syncUserSepahVerification = async (
  userOrId,
  { throwOnLookupFailure = false } = {},
) => {
  const userId = userOrId?._id || userOrId;
  const user =
    userOrId?._id && typeof userOrId?.toObject === "function"
      ? userOrId
      : await models.user.findById(userId).populate("role");

  if (!user?._id) {
    return {
      user: null,
      isSepahVerified: false,
      partyId: null,
      message: "کاربر یافت نشد.",
      payload: null,
    };
  }

  const identifier = getUserIdentifier(user);

  if (!identifier) {
    if (user.isSepahVerified !== false) {
      await models.user.updateOne(
        { _id: user._id },
        { $set: { isSepahVerified: false } },
      );
      user.isSepahVerified = false;
    }

    return {
      user,
      isSepahVerified: false,
      partyId: null,
      message: "شناسه هویتی کاربر کامل نیست.",
      payload: null,
    };
  }

  try {
    const payload = await sepahBrokerServices.getCustomerByNationalCode(
      identifier,
    );
    const status = resolveSepahCustomerStatus(payload);

    if (user.isSepahVerified !== status.isSepahVerified) {
      await models.user.updateOne(
        { _id: user._id },
        { $set: { isSepahVerified: status.isSepahVerified } },
      );
      user.isSepahVerified = status.isSepahVerified;
    }

    return {
      user,
      ...status,
    };
  } catch (error) {
    if (throwOnLookupFailure) {
      throw error;
    }

    return {
      user,
      isSepahVerified: Boolean(user.isSepahVerified),
      partyId: null,
      message: error?.message || "خطا در بررسی وضعیت ثبت نام کارگزاری سپه.",
      payload: null,
      error,
    };
  }
};
