import { cleanFilters } from '@/utils/clean-filters'
import { useMutation, useQuery } from '@tanstack/vue-query'
import {
  apiAddAdminSession,
  apiDeleteAdminSession,
  apiGetAdminSessions,
  apiGetSessionAttendance,
  apiShowAdminSession,
  apiUpdateAdminSession,
} from '@/services/api/admin-sessions'

export const adminSessionsKeys = {
  all: ['admin', 'sessions'],
  list: (filters, pagination) => ['admin', 'sessions', 'list', filters, pagination],
  detail: (id) => ['admin', 'sessions', 'detail', id],
  attendance: (sessionId, filters, pagination) => [
    'admin',
    'sessions',
    'attendance',
    sessionId,
    filters,
    pagination,
  ],
}

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

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

export const useAdminSessionAttendanceQuery = (
  sessionIdRef,
  filtersRef,
  paginationRef,
  options = {}
) =>
  useQuery({
    queryKey: ['admin', 'sessions', 'attendance', sessionIdRef, filtersRef, paginationRef],
    queryFn: () =>
      apiGetSessionAttendance(sessionIdRef.value, {
        ...cleanFilters(filtersRef?.value || {}),
        ...paginationRef?.value,
      }),
    ...options,
  })

export const useAddAdminSessionMutation = () =>
  useMutation({ mutationFn: (payload) => apiAddAdminSession(payload) })

export const useUpdateAdminSessionMutation = () =>
  useMutation({
    mutationFn: ({ id, payload }) => apiUpdateAdminSession(id, payload),
  })

export const useDeleteAdminSessionMutation = () =>
  useMutation({ mutationFn: (id) => apiDeleteAdminSession(id) })
