import { useMutation, useQueryClient, } from '@tanstack/react-query';
import { NullSeamClientError, useSeamClient } from '../../../lib/seam/use-seam-client.js';
export function useUpdateAccessCode() {
    const { client } = useSeamClient();
    const queryClient = useQueryClient();
    return useMutation({
        mutationFn: async (mutationParams) => {
            if (client === null)
                throw new NullSeamClientError();
            return await client.accessCodes.update(mutationParams);
        },
        onSuccess: (_data, variables) => {
            // There is no guarantee that the actual code has updated even if the
            // request was succesful. To prevent stale data in the UI, the
            // code below optimistically updates the data in cache.
            queryClient.setQueryData(['access_codes', 'get', { access_code_id: variables.access_code_id }], (accessCode) => {
                if (accessCode == null) {
                    return;
                }
                return {
                    ...accessCode,
                    code: variables.code ?? accessCode.code,
                    name: variables.name ?? accessCode.name,
                };
            });
            queryClient.setQueryData(['access_codes', 'list', { device_id: variables.device_id }], (accessCodes) => {
                if (accessCodes == null) {
                    return;
                }
                return accessCodes.map((accessCode) => {
                    if (accessCode.access_code_id === variables.access_code_id) {
                        return {
                            ...accessCode,
                            code: variables.code ?? accessCode.code,
                            name: variables.name ?? accessCode.name,
                        };
                    }
                    return accessCode;
                });
            });
        },
    });
}
//# sourceMappingURL=use-update-access-code.js.map