import { useMutation, useQueryClient, type UseMutationOptions } from '@tanstack/react-query' import { toast } from 'sonner' import { storageKeys } from '../keys' import { handleError, post } from '@/data/fetchers' import type { StudioError } from '@/lib/errors/studio-errors' export type ObjectVersionRestoreVariables = { projectRef: string bucketId: string /** The object's full path within the bucket, not just its leaf name. */ path: string versionId: string } /** A move onto the object's own path: Storage consumes the source rather than copying it. */ async function restoreObjectVersion({ projectRef, bucketId, path, versionId, }: ObjectVersionRestoreVariables) { if (!projectRef) throw new Error('projectRef is required') if (!bucketId) throw new Error('bucketId is required') if (!path) throw new Error('path is required') if (!versionId) throw new Error('versionId is required') const { error } = await post('/platform/storage/{ref}/buckets/{id}/objects/move', { params: { path: { ref: projectRef, id: bucketId } }, body: { from: path, to: path, sourceVersionId: versionId }, }) if (error) handleError(error) } export const useObjectVersionRestoreMutation = ({ onSuccess, onError, ...options }: Omit< UseMutationOptions, 'mutationFn' > = {}) => { const queryClient = useQueryClient() return useMutation({ mutationFn: restoreObjectVersion, async onSuccess(data, variables, context, mutationContext) { await queryClient.invalidateQueries({ queryKey: storageKeys.objectVersions( variables.projectRef, variables.bucketId, variables.path ), }) await onSuccess?.(data, variables, context, mutationContext) }, async onError(error, variables, context, mutationContext) { if (onError === undefined) toast.error(`Failed to restore version: ${error.message}`) else onError(error, variables, context, mutationContext) }, ...options, }) }