import { cleanFilters } from '@/utils/clean-filters'
import { useMutation, useQuery } from '@tanstack/vue-query'
import {
  apiGetStudentExamResults,
  apiGetStudentExams,
  apiShowStudentExam,
  apiStartStudentExam,
  apiSubmitStudentExamAttempt,
} from '@/services/api/student-exams'

export const studentExamsKeys = {
  list: (filters, pagination) => ['student', 'exams', 'list', filters, pagination],
  detail: (id) => ['student', 'exams', 'detail', id],
  results: (filters, pagination) => ['student', 'exams', 'results', filters, pagination],
}

export const useStudentExamsListQuery = (filtersRef, paginationRef, options = {}) =>
  useQuery({
    queryKey: ['student', 'exams', 'list', filtersRef, paginationRef],
    queryFn: () =>
      apiGetStudentExams({
        ...cleanFilters(filtersRef.value),
        ...paginationRef.value,
      }),
    select: (response) => ({
      data: response?.data?.items ?? response?.data ?? [],
      meta: response?.data?.meta ?? response?.meta,
    }),
    ...options,
  })

export const useStudentExamQuery = (idRef, options = {}) =>
  useQuery({
    queryKey: ['student', 'exams', 'detail', idRef],
    queryFn: () => apiShowStudentExam(idRef.value),
    // Bridge the backend exam shape (questionText / options[].optionText) into
    // the fields the frozen take-exam UI reads (title / answers[].title), and
    // expose passingScore for the summary card.
    select: (response) => {
      const exam = response?.data ?? response
      if (!exam) return exam
      return {
        ...exam,
        passingScore: exam.minimumScore ?? exam.passingScore,
        questions: (exam.questions || []).map((q) => ({
          ...q,
          title: q.questionText ?? q.title,
          answers: (q.options || q.answers || []).map((o) => ({
            id: o.id,
            title: o.optionText ?? o.title,
          })),
        })),
      }
    },
    ...options,
  })

export const useStudentExamResultsQuery = (filtersRef, paginationRef, options = {}) =>
  useQuery({
    queryKey: ['student', 'exams', 'results', filtersRef, paginationRef],
    queryFn: () =>
      apiGetStudentExamResults({
        ...cleanFilters(filtersRef?.value || {}),
        ...paginationRef?.value,
      }),
    select: (response) => ({
      data: response?.data?.items ?? response?.data ?? [],
      meta: response?.data?.meta ?? response?.meta,
    }),
    ...options,
  })

export const useStartStudentExamMutation = () =>
  useMutation({ mutationFn: (id) => apiStartStudentExam(id) })

export const useSubmitStudentExamAttemptMutation = () =>
  useMutation({
    mutationFn: ({ id, payload }) => apiSubmitStudentExamAttempt(id, payload),
  })
