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 useUpdateAsset(type: string, library: string) {
  const qc = useQueryClient();
  return useMutation({
    mutationFn: ({ id, patch }: { id: string; patch: Partial<CreateAssetPayload> }) =>
      assetsApi.update(id, patch),
    onSuccess: () => qc.invalidateQueries({ queryKey: assetsKey(type, library) }),
  });
}

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

export function useGenerateAssetImage(type: string, library: string) {
  const qc = useQueryClient();
  return useMutation({
    mutationFn: (id: string) => assetsApi.generateImage(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) }),
  });
}
