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

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

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

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

  return {
    quizKind: dto.quiz_kind,
    quizId: dto.quiz_id,
    quizTitle: dto.quiz_title,
    weekOf: dto.week_of,
    personalityType: dto.personality_type,
    quizAnswers: toNumericAnswerMap(dto.quiz_answers),
    score: dto.score,
    totalQuestions: dto.total_questions,
    resultLabel: dto.result_label,
    resultPayload: dto.result_payload,
    completedAt: dto.completed_at,
    updatedAt: dto.updatedAt,
  };
}

export function toPersonalityQuizResultMutationDto(
  submission: PersonalityQuizSubmission,
): PersonalityQuizResultMutationDto {
  return {
    quiz_kind: submission.quizKind,
    quiz_id: submission.quizId,
    quiz_title: submission.quizTitle,
    personality_type: submission.personalityType ?? null,
    quiz_answers: toStringAnswerMap(submission.quizAnswers),
    score: submission.score ?? null,
    total_questions: submission.totalQuestions,
    result_label: submission.resultLabel ?? submission.personalityType ?? null,
    result_payload: submission.resultPayload,
  };
}
