import { useMutation, useQueryClient } from '@tanstack/react-query';
import { authKeys } from '@/services/auth/keys';
import { profilesApi } from '../apis';
import { profileKeys } from '../keys';
import type { UpsertCustomerProfileInput } from '../types';

/**
 * Creates/updates the customer profile. Writes the fresh profile straight into cache and
 * invalidates `/me` so a profile-completion change reflects in the Home nudge (b3 also
 * auto-provisions a thin customer profile, flipping `hasCustomerProfile`).
 */
export function useUpsertCustomerProfile() {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: (input: UpsertCustomerProfileInput) => profilesApi.upsertCustomerProfile(input),
    onSuccess: (profile) => {
      queryClient.setQueryData(profileKeys.customer(), profile);
      queryClient.invalidateQueries({ queryKey: authKeys.me() });
    },
  });
}
