import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { inquiriesApi, type ListInquiriesParams, type CreateInquiryDto } from '@/lib/inquiries-api';

export const inquiriesKeys = {
  all: ['inquiries'] as const,
  myInquiries: (params: ListInquiriesParams) => ['inquiries', 'my', params] as const,
  byListing: (listingId: string, params: ListInquiriesParams) =>
    ['inquiries', 'listing', listingId, params] as const,
};

export function useMyInquiries(params: ListInquiriesParams = {}) {
  return useQuery({
    queryKey: inquiriesKeys.myInquiries(params),
    queryFn: () => inquiriesApi.getMyInquiries(params),
  });
}

export function useInquiriesByListing(listingId: string, params: ListInquiriesParams = {}) {
  return useQuery({
    queryKey: inquiriesKeys.byListing(listingId, params),
    queryFn: () => inquiriesApi.getByListing(listingId, params),
    enabled: !!listingId,
  });
}

export function useMarkInquiryRead() {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: (id: string) => inquiriesApi.markAsRead(id),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: inquiriesKeys.all });
    },
  });
}

export function useCreateInquiry() {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: (data: CreateInquiryDto) => inquiriesApi.create(data),
    onSuccess: (_data, variables) => {
      queryClient.invalidateQueries({ queryKey: inquiriesKeys.all });
      queryClient.invalidateQueries({
        queryKey: inquiriesKeys.byListing(variables.listingId, {}),
      });
    },
  });
}
