import { cleanFilters } from '@/utils/clean-filters'
import { useMutation, useQuery } from '@tanstack/vue-query'
import {
  apiAddAdminCourse,
  apiDeleteAdminCourse,
  apiGetAdminCourses,
  apiShowAdminCourse,
  apiUpdateAdminCourse,
} from '@/services/api/admin-courses'

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

export const useAdminCoursesListQuery = (filtersRef, paginationRef, options = {}) =>
  useQuery({
    queryKey: ['admin', 'courses', 'list', filtersRef, paginationRef],
    queryFn: () =>
      apiGetAdminCourses({ ...cleanFilters(filtersRef.value), ...paginationRef.value }),
    select: (response) => ({
      data: response?.data?.items ?? response?.data ?? [],
      meta: response?.data?.meta ?? response?.meta,
    }),
    ...options,
  })

export const useAdminCourseQuery = (idRef, options = {}) =>
  useQuery({
    queryKey: ['admin', 'courses', 'detail', idRef],
    queryFn: () => apiShowAdminCourse(idRef.value),
    select: (response) => response?.data ?? response,
    ...options,
  })

export const useAddAdminCourseMutation = () =>
  useMutation({ mutationFn: (payload) => apiAddAdminCourse(payload) })

export const useUpdateAdminCourseMutation = () =>
  useMutation({
    mutationFn: ({ id, payload }) => apiUpdateAdminCourse(id, payload),
  })

export const useDeleteAdminCourseMutation = () =>
  useMutation({ mutationFn: (id) => apiDeleteAdminCourse(id) })
