// src/hooks/mutations/useCreateShoppingListMutation.ts
import { useMutation, useQueryClient } from '@tanstack/react-query';
import * as apiClient from '../../services/apiClient';
import { notifySuccess, notifyError } from '../../services/notificationService';
import { queryKeyBases } from '../../config/queryKeys';

interface CreateShoppingListParams {
  name: string;
}

/**
 * Mutation hook for creating a new shopping list.
 *
 * This hook provides automatic cache invalidation. When the mutation succeeds,
 * it invalidates the shopping-lists query to trigger a refetch of the updated list.
 *
 * @returns Mutation object with mutate function and state
 *
 * @example
 * ```tsx
 * const createShoppingList = useCreateShoppingListMutation();
 *
 * const handleCreate = () => {
 *   createShoppingList.mutate(
 *     { name: 'Weekly Groceries' },
 *     {
 *       onSuccess: (newList) => console.log('Created:', newList),
 *       onError: (error) => console.error(error),
 *     }
 *   );
 * };
 * ```
 */
export const useCreateShoppingListMutation = () => {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: async ({ name }: CreateShoppingListParams) => {
      const response = await apiClient.createShoppingList(name);

      if (!response.ok) {
        const error = await response.json().catch(() => ({
          message: `Request failed with status ${response.status}`,
        }));
        throw new Error(error.message || 'Failed to create shopping list');
      }

      return response.json();
    },
    onSuccess: () => {
      // Invalidate and refetch shopping lists to get the updated list
      queryClient.invalidateQueries({ queryKey: queryKeyBases.shoppingLists });
      notifySuccess('Shopping list created');
    },
    onError: (error: Error) => {
      notifyError(error.message || 'Failed to create shopping list');
    },
  });
};
