import { useQuery } from '@tanstack/vue-query'
import { cleanFilters } from '@/utils/clean-filters'
import {
  apiGetMissionaryPassedTerms,
  apiGetMissionaryPassedCourses,
  apiGetMissionaryPassedSessions,
} from '@/services/api/missionary-education'

// All three passed-* endpoints return the paginated `{ items, meta }` envelope,
// mirroring /student/my-terms, /courses and /sessions.
const selectList = (response) => {
  const payload = response?.data ?? response ?? {}
  return {
    data: Array.isArray(payload.items) ? payload.items : payload ?? [],
    meta: payload.meta,
  }
}

export const useMissionaryPassedTermsQuery = (paginationRef, options = {}) =>
  useQuery({
    queryKey: ['missionary', 'passed-terms', paginationRef],
    queryFn: () => apiGetMissionaryPassedTerms({ ...paginationRef.value }),
    select: selectList,
    ...options,
  })

export const useMissionaryPassedCoursesQuery = (filtersRef, paginationRef, options = {}) =>
  useQuery({
    queryKey: ['missionary', 'passed-courses', filtersRef, paginationRef],
    queryFn: () =>
      apiGetMissionaryPassedCourses({
        ...cleanFilters(filtersRef.value),
        ...paginationRef.value,
      }),
    select: selectList,
    ...options,
  })

export const useMissionaryPassedSessionsQuery = (filtersRef, paginationRef, options = {}) =>
  useQuery({
    queryKey: ['missionary', 'passed-sessions', filtersRef, paginationRef],
    queryFn: () =>
      apiGetMissionaryPassedSessions({
        ...cleanFilters(filtersRef.value),
        ...paginationRef.value,
      }),
    select: selectList,
    ...options,
  })
