import { FieldsProcessor } from './fields-processor.js';
import { FilterableQueryBuilder } from './where-query-builder.js';
const fieldsProcessor = new FieldsProcessor();
/**
 * A query builder for updating records in the database.
 * @template DB - The database type.
 * @template TableName - The name of the table to update.
 */
export class UpdateQueryBuilder extends FilterableQueryBuilder {
    #node;
    constructor(node, executor) {
        super(node, executor);
        this.#node = node;
    }
    /**
     * Sets the values to update for the records that match the where clauses.
     * @param values - An object containing the fields and their new values.
     * @returns The `UpdateQueryBuilder` instance for chaining.
     *
     * @example
     * ```typescript
     * const { affectedRecords } = await qb
     *   .update('users')
     *   .set({ name: 'New Name' })
     *   .where('id', '=', 1)
     *   .execute();
     * ```
     */
    set(values) {
        const newValues = fieldsProcessor.process(values);
        return new UpdateQueryBuilder({
            ...this.#node,
            values: newValues,
        }, this._executor);
    }
    /**
     * Executes the update query.
     * @returns A promise that resolves with the number of affected records.
     *
     * @example
     * ```typescript
     * const { affectedRecords } = await qb
     *   .update('users')
     *   .set({ name: 'New Name' })
     *   .where('id', '=', 1)
     *   .execute();
     * ```
     */
    async execute() {
        const response = await this._executor.execute(this);
        return response[0];
    }
    compile() {
        const query = 'mutation ($metadata: JSON) { execute(metadata: $metadata) }';
        const metadata = [this._prepareMetadata()];
        return {
            query,
            variables: {
                metadata,
            },
        };
    }
    _prepareMetadata() {
        return {
            type: 'update',
            tableName: this.#node.tableName,
            values: this.#node.values,
            ...(this.#node.filtersSet.filtersSet.length > 0
                ? { filtersSet: this.#node.filtersSet }
                : {}),
        };
    }
}
//# sourceMappingURL=update-query-builder.js.map