"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.batchWrite = batchWrite;
exports.batchInsert = batchInsert;
const database_1 = require("../database/database");
const query_cache_1 = require("./query-cache");
function batchWrite(operations, invalidatePatterns = []) {
    const db = (0, database_1.getDb)();
    const result = { total: operations.length, errors: 0, errorMessages: [] };
    if (operations.length === 0)
        return result;
    const tx = db.transaction(() => {
        for (const op of operations) {
            try {
                db.prepare(op.sql).run(...op.params);
            }
            catch (err) {
                result.errors++;
                result.errorMessages.push(err.message);
            }
        }
    });
    tx();
    if (invalidatePatterns.length > 0)
        (0, query_cache_1.invalidateOnWrite)(invalidatePatterns);
    return result;
}
function batchInsert(table, rows, invalidatePatterns = []) {
    if (rows.length === 0)
        return { inserted: 0, errors: 0, errorMessages: [] };
    const columns = Object.keys(rows[0]);
    const placeholders = columns.map(() => '?').join(', ');
    const sql = `INSERT OR IGNORE INTO ${table} (${columns.join(', ')}) VALUES (${placeholders})`;
    const db = (0, database_1.getDb)();
    const result = { inserted: 0, errors: 0, errorMessages: [] };
    const tx = db.transaction(() => {
        const stmt = db.prepare(sql);
        for (const row of rows) {
            try {
                const params = columns.map(c => row[c] ?? null);
                const info = stmt.run(...params);
                if (info.changes > 0)
                    result.inserted++;
            }
            catch (err) {
                result.errors++;
                result.errorMessages.push(err.message);
            }
        }
    });
    tx();
    if (invalidatePatterns.length > 0)
        (0, query_cache_1.invalidateOnWrite)(invalidatePatterns);
    return result;
}
//# sourceMappingURL=batch-write.js.map