import { cleanFilters } from '@/utils/clean-filters'
import { useMutation, useQuery } from '@tanstack/vue-query'
import {
  apiGetStudentSessions,
  apiShowStudentSession,
  apiSubmitStudentHomework,
} from '@/services/api/student-sessions'

export const studentSessionsKeys = {
  list: (filters, pagination) => ['student', 'sessions', 'list', filters, pagination],
  detail: (id) => ['student', 'sessions', 'detail', id],
}

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

const adaptSessionResponse = (response) => {
  const session = response?.data ?? response ?? {}
  const media = Array.isArray(session.media) ? session.media : []
  const byCollection = (name) => media.find((m) => m.collectionName === name)
  return {
    ...session,
    videoUrl: byCollection('video')?.url ?? null,
    audioUrl: byCollection('voice')?.downloadUrl ?? null,
    pdfUrl: byCollection('pdf')?.url ?? null,
    poster: byCollection('cover')?.url ?? null,
  }
}

export const useStudentSessionQuery = (idRef, options = {}) =>
  useQuery({
    queryKey: ['student', 'sessions', 'detail', idRef],
    queryFn: () => apiShowStudentSession(idRef.value),
    select: adaptSessionResponse,
    ...options,
  })

export const useSubmitStudentHomeworkMutation = () =>
  useMutation({
    mutationFn: ({ homeworkId, payload }) => apiSubmitStudentHomework(homeworkId, payload),
  })
