import { useMutation, useQueryClient } from '@tanstack/react-query';
import { serviceAreasApi } from '../apis';
import { serviceAreaKeys } from '../keys';
import type { AddServiceAreaInput } from '../types';

/**
 * Adds a coverage area, then invalidates the list. A duplicate `(cityId, districtId)` returns
 * `409` — surfaced via `mutation.error` so the screen shows the inline "already covered" message
 * (the client-side check is the fast path; this 409 is the belt-and-braces server truth).
 */
export function useAddServiceArea() {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: (input: AddServiceAreaInput) => serviceAreasApi.add(input),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: serviceAreaKeys.lists() });
    },
  });
}
