import { useQuery } from '@tanstack/vue-query'
import { cleanFilters } from '@/utils/clean-filters'
import { apiGetStudentCourses, apiShowStudentCourse } from '@/services/api/student-courses'

export const studentCoursesKeys = {
  all: ['student', 'courses'],
  list: (filters, pagination) => ['student', 'courses', 'list', filters, pagination],
  detail: (id) => ['student', 'courses', 'detail', id],
}

const adaptCourseResponse = (response) => {
  const course = response?.data ?? response
  if (!course) return course
  return {
    ...course,
    image: course.image ?? course.coverUrl ?? null,
  }
}

export const useStudentCoursesListQuery = (filtersRef, paginationRef, options = {}) =>
  useQuery({
    queryKey: ['student', 'courses', 'list', filtersRef, paginationRef],
    queryFn: () =>
      apiGetStudentCourses({
        ...cleanFilters(filtersRef.value),
        ...paginationRef.value,
      }),
    ...options,
  })

export const useStudentCourseQuery = (idRef, options = {}) =>
  useQuery({
    queryKey: ['student', 'courses', 'detail', idRef],
    queryFn: () => apiShowStudentCourse(idRef.value),
    select: adaptCourseResponse,
    ...options,
  })
