import { useMutation, useQueryClient } from '@tanstack/react-query';
import { addressesApi } from '../apis';
import { addressKeys } from '../keys';
import type { CreateAddressInput } from '../types';

/**
 * Creates an address. Invalidates every cached list so the new card (and, if it became primary,
 * the flipped badge on the old one) reflects reality. Domain 400s (empty title/addressLine,
 * invalid city) surface via `mutation.error`; the fetch layer owns 401/403/5xx toasts.
 */
export function useCreateAddress() {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: (input: CreateAddressInput) => addressesApi.create(input),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: addressKeys.lists() });
    },
  });
}
