export const cloneAssessment = (assessment) =>
  assessment ? JSON.parse(JSON.stringify(assessment)) : null;

const hasValue = (value) => {
  if (value === null || typeof value === 'undefined') return false;
  if (typeof value === 'string') return value.trim() !== '';
  return true;
};

export const isExerciseComplete = (exercise = {}) => {
  if (exercise.subA && exercise.subB) {
    return [...(exercise.subA || []), ...(exercise.subB || [])].every(hasValue);
  }

  return (exercise.values || []).every(hasValue);
};

export const isAssessmentComplete = (assessment) => {
  if (!assessment) return false;
  if (!hasValue(assessment.name) || !hasValue(assessment.datum)) return false;

  const exercises = assessment.exercises || [];
  if (!exercises.length) return false;

  return exercises.every(isExerciseComplete);
};

export const getFinalizeDisabledReason = (assessment) => {
  if (!assessment) return 'Kein Test geöffnet';
  if (assessment.isFinalized) return 'Dieser Test wurde bereits final abgeschlossen';
  if (!hasValue(assessment.name) || !hasValue(assessment.datum)) {
    return 'Bitte zuerst Name und Datum ausfüllen';
  }
  if (!isAssessmentComplete(assessment)) {
    return 'Bitte alle Übungsfelder ausfüllen, bevor du final abschließt';
  }
  return '';
};
