"use client";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { useAuth } from "./useAuth";
function useEntityMutations(options) {
  const { entityConfig, onSuccess, onError } = options;
  const { user } = useAuth();
  const queryClient = useQueryClient();
  const baseQueryKey = ["entity", entityConfig.slug];
  const createMutation = useMutation({
    mutationFn: async (data) => {
      const response = await fetch(`/api/v1/${entityConfig.slug}`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(data)
      });
      if (!response.ok) {
        const errorData = await response.json();
        throw new Error(errorData.error || "Failed to create");
      }
      const result = await response.json();
      return result.data || result.item || result;
    },
    onMutate: async (newItem) => {
      await queryClient.cancelQueries({ queryKey: baseQueryKey });
      const previousData = queryClient.getQueriesData({ queryKey: baseQueryKey });
      queryClient.setQueriesData({ queryKey: baseQueryKey }, (old) => {
        if (!(old == null ? void 0 : old.items)) return old;
        return {
          ...old,
          items: [{ ...newItem, id: "temp-" + Date.now() }, ...old.items],
          total: old.total + 1
        };
      });
      return { previousData };
    },
    onError: (error, variables, context) => {
      if (context == null ? void 0 : context.previousData) {
        context.previousData.forEach(([queryKey, data]) => {
          queryClient.setQueryData(queryKey, data);
        });
      }
      onError == null ? void 0 : onError(error, variables);
    },
    onSuccess: (data, variables) => {
      onSuccess == null ? void 0 : onSuccess(data, variables);
    },
    onSettled: () => {
      queryClient.invalidateQueries({ queryKey: baseQueryKey });
    }
  });
  const updateMutation = useMutation({
    mutationFn: async ({ id, data }) => {
      const response = await fetch(`/api/v1/${entityConfig.slug}/${id}`, {
        method: "PATCH",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(data)
      });
      if (!response.ok) {
        const errorData = await response.json();
        throw new Error(errorData.error || "Failed to update");
      }
      const result = await response.json();
      return result.data || result.item || result;
    },
    onMutate: async ({ id, data }) => {
      await queryClient.cancelQueries({ queryKey: baseQueryKey });
      const previousData = queryClient.getQueriesData({ queryKey: baseQueryKey });
      queryClient.setQueriesData({ queryKey: baseQueryKey }, (old) => {
        if (!(old == null ? void 0 : old.items)) return old;
        return {
          ...old,
          items: old.items.map(
            (item) => item.id === id ? { ...item, ...data } : item
          )
        };
      });
      queryClient.setQueriesData({ queryKey: [...baseQueryKey, id] }, (old) => {
        if (!old) return old;
        return { ...old, ...data };
      });
      return { previousData };
    },
    onError: (error, variables, context) => {
      if (context == null ? void 0 : context.previousData) {
        context.previousData.forEach(([queryKey, data]) => {
          queryClient.setQueryData(queryKey, data);
        });
      }
      onError == null ? void 0 : onError(error, variables);
    },
    onSuccess: (data, variables) => {
      onSuccess == null ? void 0 : onSuccess(data, variables);
    },
    onSettled: () => {
      queryClient.invalidateQueries({ queryKey: baseQueryKey });
    }
  });
  const deleteMutation = useMutation({
    mutationFn: async (id) => {
      const response = await fetch(`/api/v1/${entityConfig.slug}/${id}`, {
        method: "DELETE"
      });
      if (!response.ok) {
        throw new Error("Failed to delete");
      }
      return { id };
    },
    onMutate: async (id) => {
      await queryClient.cancelQueries({ queryKey: baseQueryKey });
      const previousData = queryClient.getQueriesData({ queryKey: baseQueryKey });
      queryClient.setQueriesData({ queryKey: baseQueryKey }, (old) => {
        if (!(old == null ? void 0 : old.items)) return old;
        return {
          ...old,
          items: old.items.filter((item) => item.id !== id),
          total: old.total - 1
        };
      });
      return { previousData };
    },
    onError: (error, variables, context) => {
      if (context == null ? void 0 : context.previousData) {
        context.previousData.forEach(([queryKey, data]) => {
          queryClient.setQueryData(queryKey, data);
        });
      }
      onError == null ? void 0 : onError(error, variables);
    },
    onSuccess: (data, variables) => {
      onSuccess == null ? void 0 : onSuccess(data, variables);
    },
    onSettled: () => {
      queryClient.invalidateQueries({ queryKey: baseQueryKey });
    }
  });
  const bulkDeleteMutation = useMutation({
    mutationFn: async (ids) => {
      const response = await fetch(`/api/v1/${entityConfig.slug}/bulk`, {
        method: "DELETE",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ ids })
      });
      if (!response.ok) {
        throw new Error("Failed to bulk delete");
      }
      return { ids };
    },
    onMutate: async (ids) => {
      await queryClient.cancelQueries({ queryKey: baseQueryKey });
      const previousData = queryClient.getQueriesData({ queryKey: baseQueryKey });
      queryClient.setQueriesData({ queryKey: baseQueryKey }, (old) => {
        if (!(old == null ? void 0 : old.items)) return old;
        return {
          ...old,
          items: old.items.filter((item) => !ids.includes(item.id)),
          total: old.total - ids.length
        };
      });
      return { previousData };
    },
    onError: (error, variables, context) => {
      if (context == null ? void 0 : context.previousData) {
        context.previousData.forEach(([queryKey, data]) => {
          queryClient.setQueryData(queryKey, data);
        });
      }
      onError == null ? void 0 : onError(error, variables);
    },
    onSuccess: (data, variables) => {
      onSuccess == null ? void 0 : onSuccess(data, variables);
    },
    onSettled: () => {
      queryClient.invalidateQueries({ queryKey: baseQueryKey });
    }
  });
  return {
    create: createMutation.mutateAsync,
    update: updateMutation.mutateAsync,
    delete: deleteMutation.mutateAsync,
    bulkDelete: bulkDeleteMutation.mutateAsync,
    isCreating: createMutation.isPending,
    isUpdating: updateMutation.isPending,
    isDeleting: deleteMutation.isPending || bulkDeleteMutation.isPending
  };
}
export {
  useEntityMutations
};
