"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.BatchQueryBuilder = void 0;
const aggregation_query_builder_js_1 = require("./aggregation-query-builder.js");
const query_builder_js_1 = require("./query-builder.js");
/**
 * A query builder for executing multiple queries in a single batch.
 * @template TBuilders - An array of query builders to execute.
 */
class BatchQueryBuilder {
    #builders;
    #executor;
    constructor(builders, executor) {
        this.#builders = builders;
        this.#executor = executor;
    }
    /**
     * Executes the batch query.
     * @returns A promise that resolves with an array of the results from each query in the batch.
     *
     * @example
     * ```typescript
     * const [users, newUser] = await qb.batch([
     *   qb.selectFrom('users').select(['id', 'name']),
     *   qb.insertInto('users').values({ name: 'New User' }).returning(['id', 'name']),
     * ]).execute();
     * ```
     */
    async execute() {
        return this.#executor.execute(this);
    }
    /**
     * Subscribes to the results of the batch query.
     * This is only possible if all queries in the batch are subscribable (select and aggregate).
     * @param callback - A callback function that will be called with the results of the batch query.
     * @returns A function to unsubscribe from the query.
     *
     * @example
     * ```typescript
     * const unsubscribe = qb.batch([
     *   qb.selectFrom('users').select(['id', 'name']),
     *   qb.aggregateFrom('users').groupBy('role').metrics({ count: count('id') }),
     * ]).subscribe(([users, userAggregates]) => {
     *   console.log('Users:', users);
     *   console.log('User Aggregates:', userAggregates);
     * });
     *
     * // To stop listening for updates
     * unsubscribe();
     * ```
     */
    subscribe(callback) {
        const builders = this.#builders.filter(builder => builder instanceof aggregation_query_builder_js_1.AggregationQueryBuilder ||
            builder instanceof query_builder_js_1.QueryBuilder);
        if (builders.length !== this.#builders.length) {
            throw new Error('Batch contains non-subscribable queries (e.g., insert, update, delete)');
        }
        return this.#executor.subscribe(builders, callback);
    }
    compile() {
        const query = 'mutation ($metadata: JSON) { execute(metadata: $metadata) }';
        const metadata = this.#builders.map(builder => {
            return builder._prepareMetadata();
        });
        return {
            query,
            variables: {
                metadata,
            },
        };
    }
}
exports.BatchQueryBuilder = BatchQueryBuilder;
//# sourceMappingURL=batch-query-builder.js.map