import { useQuery } from '@tanstack/react-query';
import {
  createCommunicationEvent,
  createParentMessage,
  listCommunicationEvents,
  listParentMessages,
} from '@/shared/api/communications';
import { COMMUNICATION_QUERY_KEYS } from '@/shared/constants/communications';
import type {
  CommunicationEventCreateDto,
  CommunicationEventType,
  ParentMessageCategory,
  ParentMessageCreateDto,
} from '@/shared/types/communications';
import { getApiListRows } from '@/shared/business/apiListRows';
import { useInvalidatingMutation } from '@/shared/business/queryMutations';

export function useParentMessages(category?: ParentMessageCategory) {
  return useQuery({
    queryKey: category ? [...COMMUNICATION_QUERY_KEYS.parentMessages, category] : COMMUNICATION_QUERY_KEYS.parentMessages,
    queryFn: () => getApiListRows(listParentMessages(category)),
  });
}

export function useSendParentMessage() {
  return useInvalidatingMutation({
    mutationFn: (request: ParentMessageCreateDto) => createParentMessage(request),
    invalidateQueryKey: COMMUNICATION_QUERY_KEYS.parentMessages,
  });
}

export function useCommunicationEvents(type?: CommunicationEventType) {
  return useQuery({
    queryKey: type ? [...COMMUNICATION_QUERY_KEYS.events, type] : COMMUNICATION_QUERY_KEYS.events,
    queryFn: () => getApiListRows(listCommunicationEvents(type)),
  });
}

export function useCreateCommunicationEvent() {
  return useInvalidatingMutation({
    mutationFn: (request: CommunicationEventCreateDto) => createCommunicationEvent(request),
    invalidateQueryKey: COMMUNICATION_QUERY_KEYS.events,
  });
}
