/**
 * 敏感字段集中定义：拦截器脱敏与 SensitiveText 组件共用
 */

/** 脱敏展示后缀，明文保留在原字段 */
export const TM_TEXT_SUFFIX = '_tm_text';

/** 需要加解密的字段（与 request 拦截器 arr 一致） */
export const ENCRYPT_FIELDS = new Set([
  'account',
  'accept_tel',
  'doctor',
  'express_mobile',
  'id_card',
  'idcard',
  'mobile',
  'password',
  'patient_mobile',
  'phone',
  'open_api_key',
  'api_key',
]);

/** 需要生成 _tm_text 并默认脱敏展示的字段（encrypt_only） */
export const MASK_DISPLAY_FIELDS = ENCRYPT_FIELDS;

const PHONE_FIELDS = new Set([
  'mobile',
  'phone',
  'express_mobile',
  'patient_mobile',
  'accept_tel',
]);

const ID_CARD_FIELDS = new Set(['id_card', 'idcard']);

export interface SensitiveFieldSource {
  record?: Record<string, unknown> | null;
  field: string;
}

/**
 * 判断是否为敏感字段
 */
export function isSensitiveField(field: string): boolean {
  return MASK_DISPLAY_FIELDS.has(field);
}

/**
 * 从 record 读取明文，支持 fallback 链
 */
export function getSensitivePlainText(
  record: Record<string, unknown> | null | undefined,
  field: string,
  fallback?: SensitiveFieldSource,
): string {
  const primary = readFieldValue(record, field);
  if (primary !== '') {
    return primary;
  }
  if (fallback?.record) {
    return readFieldValue(fallback.record, fallback.field);
  }
  return '';
}

/**
 * 读取脱敏文本：优先 _tm_text，否则对明文现场脱敏
 */
export function getSensitiveMaskText(
  record: Record<string, unknown> | null | undefined,
  field: string,
  fallback?: SensitiveFieldSource,
): string {
  const tmKey = `${field}${TM_TEXT_SUFFIX}`;
  const tmFromPrimary = readFieldValue(record, tmKey);
  if (tmFromPrimary !== '') {
    return tmFromPrimary;
  }
  if (fallback?.record) {
    const tmFromFallback = readFieldValue(fallback.record, tmKey);
    if (tmFromFallback !== '') {
      return tmFromFallback;
    }
  }
  const plain = getSensitivePlainText(record, field, fallback);
  if (plain === '') {
    return '';
  }
  return maskSensitiveField(field, plain);
}

/**
 * 按字段类型生成脱敏文本
 */
export function maskSensitiveField(field: string, plainText: unknown): string {
  if (plainText == null || plainText === '') {
    return '';
  }
  const str = String(plainText);
  if (field === 'password' || field === 'api_key' || field === 'open_api_key') {
    return '*'.repeat(Math.max(str.length, 6));
  }
  if (PHONE_FIELDS.has(field)) {
    if (str.length <= 7) {
      return str;
    }
    return str.slice(0, 3) + '*'.repeat(str.length - 7) + str.slice(-4);
  }
  if (ID_CARD_FIELDS.has(field)) {
    if (str.length <= 10) {
      return str;
    }
    return str.slice(0, 6) + '*'.repeat(str.length - 10) + str.slice(-4);
  }
  // account / doctor 等通用兜底：保留前 2 + 后 2
  if (str.length <= 4) {
    return str;
  }
  return str.slice(0, 2) + '*'.repeat(str.length - 4) + str.slice(-2);
}

function readFieldValue(
  record: Record<string, unknown> | null | undefined,
  field: string,
): string {
  if (!record) {
    return '';
  }
  const value = record[field];
  if (value == null || value === '') {
    return '';
  }
  return String(value);
}
