import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import {
  createEngagement,
  deleteEngagement,
  fetchEngagement,
  listEngagements,
  patchEngagement,
} from '@/api/engagements';
import type { EngagementInput } from '@/api/types';

const KEY = ['engagements'] as const;

export function useEngagementsList() {
  return useQuery({ queryKey: KEY, queryFn: listEngagements });
}

export function useEngagement(id: number | undefined) {
  return useQuery({
    queryKey: [...KEY, id],
    queryFn: () => fetchEngagement(id as number),
    enabled: typeof id === 'number' && !Number.isNaN(id),
  });
}

export function useCreateEngagement() {
  const qc = useQueryClient();
  return useMutation({
    mutationFn: (input: EngagementInput) => createEngagement(input),
    onSuccess: () => qc.invalidateQueries({ queryKey: KEY }),
  });
}

export function usePatchEngagement(id: number) {
  const qc = useQueryClient();
  return useMutation({
    mutationFn: (input: Partial<EngagementInput>) => patchEngagement(id, input),
    onSuccess: () => {
      qc.invalidateQueries({ queryKey: KEY });
      qc.invalidateQueries({ queryKey: [...KEY, id] });
    },
  });
}

export function useDeleteEngagement() {
  const qc = useQueryClient();
  return useMutation({
    mutationFn: (id: number) => deleteEngagement(id),
    onSuccess: () => qc.invalidateQueries({ queryKey: KEY }),
  });
}
