import { cleanFilters } from '@/utils/clean-filters'
import { useMutation, useQuery } from '@tanstack/vue-query'
import {
  apiCreateStudentTicket,
  apiGetStudentTickets,
  apiGetStudentTicketStats,
  apiSendStudentTicketMessage,
  apiShowStudentTicket,
} from '@/services/api/student-tickets'

export const studentTicketsKeys = {
  all: ['student', 'tickets'],
  byType: (type) => ['student', 'tickets', 'type', type],
  list: (filters, pagination) => ['student', 'tickets', 'list', filters, pagination],
  detail: (id) => ['student', 'tickets', 'detail', id],
  stats: (params) => ['student', 'tickets', 'stats', params],
}

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

export const useStudentTicketQuery = (idRef, options = {}) =>
  useQuery({
    queryKey: ['student', 'tickets', 'detail', idRef],
    queryFn: () => apiShowStudentTicket(idRef.value),
    select: (response) => response?.data ?? response,
    ...options,
  })

// Backend returns `{ open_tickets, answered_tickets, closed_tickets, all }` —
// camelized on the wire to `{ openTickets, answeredTickets, closedTickets, all }`.
// Pass `{ type: 'ticket' | 'service' | 'advise' }` to scope the counts.
export const useStudentTicketStatsQuery = (params = {}, options = {}) =>
  useQuery({
    queryKey: studentTicketsKeys.stats(params),
    queryFn: () => apiGetStudentTicketStats(params),
    select: (response) => response?.data ?? response,
    ...options,
  })

export const useCreateStudentTicketMutation = () =>
  useMutation({ mutationFn: (payload) => apiCreateStudentTicket(payload) })

export const useSendStudentTicketMessageMutation = () =>
  useMutation({
    mutationFn: ({ id, payload }) => apiSendStudentTicketMessage(id, payload),
  })
