import md5 from "@/utils/md5";

export const FLOW_EVIDENCE_FINGERPRINT_RULE =
  "md5(leAccountNo+leAccountName+customerAccountNo+customerAccountName+trxDate+displayAmount+userMemo)";

export const MODEL_EVIDENCE_FINGERPRINT_RULE = "md5(personIdCard+modelCode)";

export const ASSET_EVIDENCE_FINGERPRINT_RULE =
  "md5(staffIdCard+totalIncome+totalDebt+totalAsset+riskLevelCode)";

function normalizeFingerprintValue(value) {
  if (value === null || value === undefined) {
    return "";
  }
  return String(value).trim();
}

function resolveCounterpartyName(detail) {
  return detail.customerAccountName || detail.customerName || detail.counterpartyName || "";
}

export function buildFlowEvidenceFingerprintSource(detail = {}) {
  return [
    detail.leAccountNo,
    detail.leAccountName,
    detail.customerAccountNo,
    resolveCounterpartyName(detail),
    detail.trxDate,
    detail.displayAmount,
    detail.userMemo,
  ]
    .map(normalizeFingerprintValue)
    .join("");
}

export function buildFlowEvidenceFingerprint(detail = {}) {
  const source = buildFlowEvidenceFingerprintSource(detail);
  return source ? md5(source) : "";
}

export function buildFlowEvidenceSnapshot(detail = {}) {
  const evidenceFingerprint = buildFlowEvidenceFingerprint(detail);
  return {
    ...detail,
    evidenceFingerprint,
    evidenceFingerprintRule: FLOW_EVIDENCE_FINGERPRINT_RULE,
  };
}

export function buildModelEvidenceFingerprint(personIdCard, modelCode) {
  const idCard = normalizeFingerprintValue(personIdCard);
  const code = normalizeFingerprintValue(modelCode);
  return idCard && code ? md5(idCard + code) : "";
}

export function buildAssetEvidenceFingerprint(row = {}) {
  const idCard = normalizeFingerprintValue(row.staffIdCard);
  const assetSource = [
    row.totalIncome,
    row.totalDebt,
    row.totalAsset,
    row.riskLevelCode,
  ]
    .map(normalizeFingerprintValue)
    .join("");
  return idCard && assetSource ? md5(idCard + assetSource) : "";
}

export function buildAssetEvidenceSnapshot(row = {}, detail = {}, summary = {}) {
  const evidenceFingerprint = buildAssetEvidenceFingerprint(row);
  return {
    row,
    detail,
    summary,
    evidenceFingerprint,
    evidenceFingerprintRule: ASSET_EVIDENCE_FINGERPRINT_RULE,
  };
}
