import type {
  PersonalityQuizResultDto,
  PersonalityQuizResultMutationDto,
} from '@/shared/types/personality';
import type {
  PersonalityQuizResultViewModel,
  PersonalityQuizSubmission,
} from '@/business/personality/types';

function toNumericAnswerMap(answers: Record<string, string>): Record<number, string> {
  return Object.entries(answers).reduce<Record<number, string>>((result, [key, value]) => {
    result[Number(key)] = value;
    return result;
  }, {});
}

function toStringAnswerMap(answers: Record<number, string>): Record<string, string> {
  return Object.entries(answers).reduce<Record<string, string>>((result, [key, value]) => {
    result[key] = value;
    return result;
  }, {});
}

export function toPersonalityQuizResultViewModel(
  dto: PersonalityQuizResultDto | null,
): PersonalityQuizResultViewModel | null {
  if (!dto) {
    return null;
  }

  return {
    personalityType: dto.personality_type,
    quizAnswers: toNumericAnswerMap(dto.quiz_answers),
    updatedAt: dto.updatedAt,
  };
}

export function toPersonalityQuizResultMutationDto(
  submission: PersonalityQuizSubmission,
): PersonalityQuizResultMutationDto {
  return {
    personality_type: submission.personalityType,
    quiz_answers: toStringAnswerMap(submission.quizAnswers),
  };
}
