import { useMutation, UseMutationOptions, useQueryClient } from '@tanstack/react-query' import { toast } from 'sonner' import { awsAccountKeys } from './keys' import { handleError, post } from '@/data/fetchers' import type { StudioError } from '@/lib/errors/studio-errors' export type AWSAccountCreateVariables = { projectRef: string awsAccountId: string accountName?: string databaseIdentifier?: string } export async function createAWSAccount({ projectRef, awsAccountId, accountName, databaseIdentifier, }: AWSAccountCreateVariables) { const { data, error } = await post( '/platform/projects/{ref}/privatelink/associations/aws-account', { params: { path: { ref: projectRef }, }, body: { aws_account_id: awsAccountId, account_name: accountName, database_identifier: databaseIdentifier, }, } ) if (error) handleError(error) return data } type AWSAccountCreateData = Awaited> export const useAWSAccountCreateMutation = ({ onSuccess, onError, ...options }: Omit< UseMutationOptions, 'mutationFn' > = {}) => { const queryClient = useQueryClient() return useMutation({ mutationFn: (vars) => createAWSAccount(vars), async onSuccess(data, variables, context, mutationContext) { const { projectRef } = variables await queryClient.invalidateQueries({ queryKey: awsAccountKeys.list(projectRef) }) await onSuccess?.(data, variables, context, mutationContext) }, async onError(data, variables, context, mutationContext) { if (onError === undefined) { toast.error(`Failed to create connection: ${data.message}`) } else { onError(data, variables, context, mutationContext) } }, ...options, }) }