import QueryError from "../../errors/QueryError.js";
import StateQueryReadModel from "./StateQueryReadModel.js";
export default class LiveQueryReadModelProvider {
    #ensureFreshState;
    #currentState;
    #stateHash;
    #neighborProvider;
    #boundedReadModelProvider;
    constructor(params) {
        this.#ensureFreshState = params.ensureFreshState;
        this.#currentState = params.currentState;
        this.#stateHash = params.stateHash;
        this.#neighborProvider = params.neighborProvider;
        this.#boundedReadModelProvider = params.boundedReadModelProvider ?? null;
    }
    async openQueryReadModel(request) {
        const bounded = await this.#openBoundedReadModel(request);
        if (bounded !== null) {
            return bounded;
        }
        await this.#ensureFreshState();
        const state = this.#currentState();
        const neighborProvider = this.#neighborProvider();
        if (state === null) {
            throw new QueryError('query read model source has no current state', {
                code: 'E_QUERY_READ_MODEL_STATE',
            });
        }
        return new StateQueryReadModel({
            state,
            stateHash: await this.#stateHash(state),
            visibility: { match: '*' },
            ...(neighborProvider !== null ? { neighborProvider } : {}),
        });
    }
    async #openBoundedReadModel(request) {
        if (request === undefined || this.#boundedReadModelProvider === null) {
            return null;
        }
        return await this.#boundedReadModelProvider(request);
    }
}
