function isEmpty(v) {
  if (v === null || v === undefined) return true;
  if (Array.isArray(v)) return v.length === 0;
  if (typeof v === 'string') return v.trim() === '';
  return false;
}

const ALIAS_MAP = {
  outpatient: {
    diagnosisName: 'diagnosis',
    medicalHistorySummary: 'medicalHistory',
  },
  inhospital: {
    diagnosisName: 'diagnosis',
    medicalHistorySummary: 'medicalHistory',
    operationDate: 'surgeryDate',
    operation: 'surgeryName',
  },
  physicalExaminationTemplate: {
    inspectTime: 'inspectDate',
    inspectSummary: 'summary',
  },
  preConsultationRecord: {
    presentIllnessHistory: 'presentIllness',
    pastMedicalHistory: 'pastHistory',
  },
  preConsultationRecord: {
    presentIllnessHistory: 'presentIllness',
    pastMedicalHistory: 'pastHistory',
  },
};

export function normalizeVisitRecordFormData(templateType, raw) {
  const input = raw && typeof raw === 'object' ? raw : {};
  const out = { ...input };
  const map = ALIAS_MAP[String(templateType || '')] || {};

  Object.entries(map).forEach(([from, to]) => {
    if (isEmpty(out[to]) && !isEmpty(out[from])) out[to] = out[from];
  });

  return out;
}
