import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import {
  leadsApi,
  type CreateLeadPayload,
  type LeadStatus,
  type ListLeadsParams,
} from '@/lib/leads-api';

export const leadsKeys = {
  all: ['leads'] as const,
  list: (params: ListLeadsParams) => ['leads', 'list', params] as const,
  stats: () => ['leads', 'stats'] as const,
};

export function useLeads(params: ListLeadsParams = {}) {
  return useQuery({
    queryKey: leadsKeys.list(params),
    queryFn: () => leadsApi.getLeads(params),
  });
}

export function useLeadStats() {
  return useQuery({
    queryKey: leadsKeys.stats(),
    queryFn: () => leadsApi.getStats(),
  });
}

export function useCreateLead() {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: (data: CreateLeadPayload) => leadsApi.create(data),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: leadsKeys.all });
    },
  });
}

export function useUpdateLeadStatus() {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: ({ id, status }: { id: string; status: LeadStatus }) =>
      leadsApi.updateStatus(id, status),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: leadsKeys.all });
    },
  });
}

export function useDeleteLead() {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: (id: string) => leadsApi.delete(id),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: leadsKeys.all });
    },
  });
}
