export const SEPAH_BROKER_EXTERNAL_SOURCE = "sepah_broker";
export const SEPAH_BROKER_FUND_CODES = Object.freeze([
  "11530",
  "11222",
  "11197",
]);
const SEPAH_BROKER_FUND_REF_BY_CODE = Object.freeze({
  11530: 1,
  11197: 2,
  11222: 3,
});

const normalizeFundRegisterCode = (fundRegisterCode) =>
  String(fundRegisterCode || "").trim();

export const isSepahBrokerFund = (fundRegisterCode) =>
  SEPAH_BROKER_FUND_CODES.includes(normalizeFundRegisterCode(fundRegisterCode));

export const resolveSepahBrokerFundRef = (fundRegisterCode) => {
  const normalizedFundRegisterCode =
    normalizeFundRegisterCode(fundRegisterCode);

  if (!normalizedFundRegisterCode) {
    return null;
  }

  return SEPAH_BROKER_FUND_REF_BY_CODE[normalizedFundRegisterCode] ?? null;
};

export const assertSepahBrokerFundRef = (fundRegisterCode) => {
  const fundRef = resolveSepahBrokerFundRef(fundRegisterCode);

  if (fundRef !== null) {
    return fundRef;
  }

  const error = new Error(
    `FundRef for Sepah broker fund ${normalizeFundRegisterCode(fundRegisterCode)} is invalid.`,
  );
  error.status = 422;
  throw error;
};
