import { useMutation, useQueryClient, } from '@tanstack/react-query';
import { NullSeamClientError, useSeamClient } from '../../../lib/seam/use-seam-client.js';
export function useToggleLock(params = {}) {
    const { client } = useSeamClient();
    const queryClient = useQueryClient();
    return useMutation({
        mutationFn: async (variables) => {
            const { device_id: deviceId, properties: { locked }, } = variables;
            if (client === null)
                throw new NullSeamClientError();
            if (locked == null)
                return;
            if (locked)
                await client.locks.unlockDoor({ device_id: deviceId });
            if (!locked)
                await client.locks.lockDoor({ device_id: deviceId });
        },
        onMutate: (variables) => {
            queryClient.setQueryData(['devices', 'list', {}], (devices) => {
                if (devices == null) {
                    return devices;
                }
                return devices.map((device) => {
                    if (device.device_id !== variables.device_id ||
                        device.properties.locked == null) {
                        return device;
                    }
                    return {
                        ...device,
                        properties: {
                            ...device.properties,
                            locked: !variables.properties.locked,
                        },
                    };
                });
            });
            queryClient.setQueryData(['devices', 'get', { device_id: variables.device_id }], (device) => {
                if (device?.properties.locked == null)
                    return device;
                return {
                    ...device,
                    properties: {
                        ...device.properties,
                        locked: !variables.properties.locked,
                    },
                };
            });
        },
        onError: async (_error, variables) => {
            params.onError?.();
            await queryClient.invalidateQueries({
                queryKey: ['devices', 'list'],
            });
            await queryClient.invalidateQueries({
                queryKey: ['devices', 'get', { device_id: variables.device_id }],
            });
        },
        onSuccess() {
            params.onSuccess?.();
        },
    });
}
//# sourceMappingURL=use-toggle-lock.js.map