import { useMutation, useQueryClient } from "@tanstack/vue-query";
import { requests } from "../../../api/agent";
import { queryKeys } from "../../../api/query-keys";
import { useInvalidateShootings } from "./use-invalidate-shootings";
import { useToast } from "../../../utils/composables/use-toast";
import { BaseComposableOption } from "../../../types/composable.types";

interface ToggleFavoriteParams {
  photoId: string;
  isFavorite: boolean;
}

export const useToggleFavorite = (
  options: BaseComposableOption<{
    customerId: string;
  }> = {}
) => {
  const queryClient = useQueryClient();
  const { invalidateShootings } = useInvalidateShootings();
  const toast = useToast();

  const mutation = useMutation({
    mutationFn: async ({ photoId, isFavorite }: ToggleFavoriteParams) => {
      if (isFavorite) {
        return await requests.delete(
          `photos/${photoId}/${options.payload?.customerId}/favorite`
        );
      } else {
        return await requests.post(`photos/${photoId}/favorite`, {
          customerId: options.payload?.customerId,
        });
      }
    },
    onSuccess: async (data) => {
      await queryClient.invalidateQueries({
        queryKey: queryKeys.shootings.favorites,
      });
      // L'état favori est aussi porté par le détail du shooting.
      await invalidateShootings();

      options.onSuccess?.(data);
    },
    onError: (error) => {
      toast.error({
        message: "Erreur lors de la mise à jour des favoris",
      });
      options.onError?.(error);
    },
  });

  const toggleFavorite = async (photoId: string, isFavorite: boolean) => {
    try {
      await mutation.mutateAsync({ photoId, isFavorite });
      return true;
    } catch {
      return false;
    }
  };

  return {
    toggleFavorite,
    isLoading: mutation.isPending,
  };
};
