import { useQuery } from '@tanstack/react-query';
import {
  cancelCommunicationEvent,
  createCommunicationEvent,
  deleteCommunicationEvent,
  listCommunicationEvents,
  updateCommunicationEvent,
} from '@/shared/api/communications';
import { COMMUNICATION_QUERY_KEYS } from '@/shared/constants/communications';
import type {
  CommunicationEventCancelDto,
  CommunicationEventCreateDto,
  CommunicationEventUpdateDto,
  CommunicationEventType,
} from '@/shared/types/communications';
import { getApiListRows } from '@/shared/business/apiListRows';
import { useInvalidatingMutation } from '@/shared/business/queryMutations';

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,
  });
}

export function useUpdateCommunicationEvent() {
  return useInvalidatingMutation({
    mutationFn: (request: CommunicationEventUpdateDto) => updateCommunicationEvent(request),
    invalidateQueryKey: COMMUNICATION_QUERY_KEYS.events,
  });
}

export function useDeleteCommunicationEvent() {
  return useInvalidatingMutation({
    mutationFn: (id: string) => deleteCommunicationEvent(id),
    invalidateQueryKey: COMMUNICATION_QUERY_KEYS.events,
  });
}

export function useCancelCommunicationEvent() {
  return useInvalidatingMutation({
    mutationFn: (request: CommunicationEventCancelDto) => cancelCommunicationEvent(request),
    invalidateQueryKey: COMMUNICATION_QUERY_KEYS.events,
  });
}
