import { ref } from 'vue';
import { createIdempotentCommand } from '../commands/idempotency';
export function useOptimisticCommand(execute) {
    const pending = ref(false);
    const conflict = ref(false);
    const lastCorrelationId = ref();
    async function run(request) {
        if (pending.value)
            throw new Error('Command is already in progress');
        pending.value = true;
        conflict.value = false;
        try {
            const headers = { 'Idempotency-Key': request.idempotencyKey };
            if (request.etag)
                headers['If-Match'] = request.etag;
            const response = await execute(request, headers);
            lastCorrelationId.value = response.correlationId;
            return response;
        }
        catch (error) {
            const status = error?.response?.status;
            if (status === 409 || status === 412)
                conflict.value = true;
            throw error;
        }
        finally {
            pending.value = false;
        }
    }
    function createRequest(payload, etag) {
        return Object.freeze({ ...createIdempotentCommand(payload), etag });
    }
    return { pending, conflict, lastCorrelationId, createRequest, run };
}
