import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { assetsApi, type CreateAssetPayload } from "../lib/api/assets";

const assetsKey = (type: string, library: string) => ["global-assets", type, library];

export function useGlobalAssets(type: string, library: string) {
  return useQuery({
    queryKey: assetsKey(type, library),
    queryFn: () => assetsApi.list(type, library),
    staleTime: 30_000,
  });
}

export function useCreateAsset(type: string, library: string) {
  const qc = useQueryClient();
  return useMutation({
    mutationFn: (payload: CreateAssetPayload) => assetsApi.create(payload),
    onSuccess: () => qc.invalidateQueries({ queryKey: assetsKey(type, library) }),
  });
}

export function useToggleFavorite(type: string, library: string) {
  const qc = useQueryClient();
  return useMutation({
    mutationFn: (id: string) => assetsApi.toggleFavorite(id),
    onSuccess: () => qc.invalidateQueries({ queryKey: assetsKey(type, library) }),
  });
}

export function useDeleteAsset(type: string, library: string) {
  const qc = useQueryClient();
  return useMutation({
    mutationFn: (id: string) => assetsApi.delete(id),
    onSuccess: () => qc.invalidateQueries({ queryKey: assetsKey(type, library) }),
  });
}
