/**
 * Knowledge Vault Repository SQLite Implementation
 */
import Database from 'better-sqlite3';
import {} from '../../../domains/memory/repositories/knowledge-vault-repository.interface.js';
export class KnowledgeVaultRepositorySqlite {
    db;
    constructor(db) {
        this.db = db;
    }
    /**
     * Knowledge Vault 생성
     */
    async create(input) {
        const { vault_id, agent_id = 'default', key, value, immutable = true, version = 1, previous_version_id = null, admin_override = false, deleted_at = null, origin_source = null } = input;
        this.db.prepare(`
      INSERT INTO knowledge_vault (
        vault_id, agent_id, key, value, immutable, version,
        previous_version_id, admin_override, deleted_at, origin_source
      )
      VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
    `).run(vault_id, agent_id, key, value, immutable ? 1 : 0, version, previous_version_id, admin_override ? 1 : 0, deleted_at, origin_source);
        const result = await this.findById(vault_id);
        if (!result) {
            throw new Error(`Failed to create knowledge vault with id: ${vault_id}`);
        }
        return result;
    }
    /**
     * ID로 Knowledge Vault 조회
     */
    async findById(vault_id) {
        const result = this.db.prepare(`
      SELECT 
        vault_id,
        agent_id,
        key,
        value,
        immutable,
        version,
        previous_version_id,
        admin_override,
        deleted_at,
        origin_source,
        created_at,
        updated_at
      FROM knowledge_vault
      WHERE vault_id = ?
    `).get(vault_id);
        if (!result) {
            return null;
        }
        return {
            ...result,
            immutable: Boolean(result.immutable),
            admin_override: Boolean(result.admin_override)
        };
    }
    /**
     * agent_id와 key로 활성 버전 조회 (deleted_at IS NULL인 최신 버전)
     */
    async findActiveByKey(agent_id, key) {
        const result = this.db.prepare(`
      SELECT 
        vault_id,
        agent_id,
        key,
        value,
        immutable,
        version,
        previous_version_id,
        admin_override,
        deleted_at,
        origin_source,
        created_at,
        updated_at
      FROM knowledge_vault
      WHERE agent_id = ? AND key = ? AND deleted_at IS NULL
      ORDER BY version DESC
      LIMIT 1
    `).get(agent_id, key);
        if (!result) {
            return null;
        }
        return {
            ...result,
            immutable: Boolean(result.immutable),
            admin_override: Boolean(result.admin_override)
        };
    }
    /**
     * agent_id와 key로 특정 버전 조회
     */
    async findByKeyAndVersion(agent_id, key, version) {
        const result = this.db.prepare(`
      SELECT 
        vault_id,
        agent_id,
        key,
        value,
        immutable,
        version,
        previous_version_id,
        admin_override,
        deleted_at,
        origin_source,
        created_at,
        updated_at
      FROM knowledge_vault
      WHERE agent_id = ? AND key = ? AND version = ?
    `).get(agent_id, key, version);
        if (!result) {
            return null;
        }
        return {
            ...result,
            immutable: Boolean(result.immutable),
            admin_override: Boolean(result.admin_override)
        };
    }
    /**
     * agent_id와 key로 모든 버전 조회 (삭제된 것 포함)
     */
    async findAllVersionsByKey(agent_id, key) {
        const results = this.db.prepare(`
      SELECT 
        vault_id,
        agent_id,
        key,
        value,
        immutable,
        version,
        previous_version_id,
        admin_override,
        deleted_at,
        origin_source,
        created_at,
        updated_at
      FROM knowledge_vault
      WHERE agent_id = ? AND key = ?
      ORDER BY version ASC
    `).all(agent_id, key);
        return results.map(result => ({
            ...result,
            immutable: Boolean(result.immutable),
            admin_override: Boolean(result.admin_override)
        }));
    }
    /**
     * agent_id로 모든 활성 Knowledge Vault 조회 (deleted_at IS NULL)
     */
    async findActiveByAgentId(agent_id) {
        const results = this.db.prepare(`
      SELECT 
        vault_id,
        agent_id,
        key,
        value,
        immutable,
        version,
        previous_version_id,
        admin_override,
        deleted_at,
        origin_source,
        created_at,
        updated_at
      FROM knowledge_vault
      WHERE agent_id = ? AND deleted_at IS NULL
      ORDER BY key, version DESC
    `).all(agent_id);
        // 각 key별 최신 버전만 반환
        const latestByKey = new Map();
        for (const result of results) {
            const existing = latestByKey.get(result.key);
            if (!existing || result.version > existing.version) {
                latestByKey.set(result.key, result);
            }
        }
        return Array.from(latestByKey.values()).map(result => ({
            ...result,
            immutable: Boolean(result.immutable),
            admin_override: Boolean(result.admin_override)
        }));
    }
    /**
     * agent_id로 모든 Knowledge Vault 조회 (삭제된 것 포함)
     */
    async findByAgentId(agent_id) {
        const results = this.db.prepare(`
      SELECT 
        vault_id,
        agent_id,
        key,
        value,
        immutable,
        version,
        previous_version_id,
        admin_override,
        deleted_at,
        origin_source,
        created_at,
        updated_at
      FROM knowledge_vault
      WHERE agent_id = ?
      ORDER BY key, version ASC
    `).all(agent_id);
        return results.map(result => ({
            ...result,
            immutable: Boolean(result.immutable),
            admin_override: Boolean(result.admin_override)
        }));
    }
    /**
     * Knowledge Vault 업데이트 (immutable=true인 경우 제한)
     */
    async update(vault_id, input) {
        const existing = await this.findById(vault_id);
        if (!existing) {
            return null;
        }
        // immutable=true이고 admin_override=false인 경우 업데이트 불가
        if (existing.immutable && !existing.admin_override && !input.admin_override) {
            throw new Error(`Cannot update immutable knowledge vault: ${vault_id}`);
        }
        const updates = [];
        const values = [];
        if (input.value !== undefined) {
            updates.push('value = ?');
            values.push(input.value);
        }
        if (input.immutable !== undefined) {
            updates.push('immutable = ?');
            values.push(input.immutable ? 1 : 0);
        }
        if (input.admin_override !== undefined) {
            updates.push('admin_override = ?');
            values.push(input.admin_override ? 1 : 0);
        }
        if (input.origin_source !== undefined) {
            updates.push('origin_source = ?');
            values.push(input.origin_source);
        }
        if (updates.length === 0) {
            return existing;
        }
        values.push(vault_id);
        this.db.prepare(`
      UPDATE knowledge_vault
      SET ${updates.join(', ')}
      WHERE vault_id = ?
    `).run(...values);
        return this.findById(vault_id);
    }
    /**
     * Knowledge Vault 삭제 (soft delete: deleted_at 설정)
     */
    async delete(vault_id) {
        const existing = await this.findById(vault_id);
        if (!existing) {
            return false;
        }
        // immutable=true이고 admin_override=false인 경우 삭제 불가
        if (existing.immutable && !existing.admin_override) {
            throw new Error(`Cannot delete immutable knowledge vault: ${vault_id}`);
        }
        const result = this.db.prepare(`
      UPDATE knowledge_vault
      SET deleted_at = CURRENT_TIMESTAMP
      WHERE vault_id = ?
    `).run(vault_id);
        return result.changes > 0;
    }
    /**
     * agent_id와 key로 활성 버전 삭제 (soft delete)
     */
    async deleteActiveByKey(agent_id, key) {
        const active = await this.findActiveByKey(agent_id, key);
        if (!active) {
            return false;
        }
        // immutable=true이고 admin_override=false인 경우 삭제 불가
        if (active.immutable && !active.admin_override) {
            throw new Error(`Cannot delete immutable knowledge vault: agent_id=${agent_id}, key=${key}`);
        }
        const result = this.db.prepare(`
      UPDATE knowledge_vault
      SET deleted_at = CURRENT_TIMESTAMP
      WHERE agent_id = ? AND key = ? AND deleted_at IS NULL
    `).run(agent_id, key);
        return result.changes > 0;
    }
    /**
     * 하드 삭제 (물리적 삭제, 주의 필요)
     */
    async hardDelete(vault_id) {
        const result = this.db.prepare(`
      DELETE FROM knowledge_vault
      WHERE vault_id = ?
    `).run(vault_id);
        return result.changes > 0;
    }
    /**
     * 모든 Knowledge Vault 조회 (관리용, 삭제된 것 포함)
     */
    async findAll() {
        const results = this.db.prepare(`
      SELECT 
        vault_id,
        agent_id,
        key,
        value,
        immutable,
        version,
        previous_version_id,
        admin_override,
        deleted_at,
        origin_source,
        created_at,
        updated_at
      FROM knowledge_vault
      ORDER BY agent_id, key, version ASC
    `).all();
        return results.map(result => ({
            ...result,
            immutable: Boolean(result.immutable),
            admin_override: Boolean(result.admin_override)
        }));
    }
    /**
     * 활성 Knowledge Vault만 조회 (deleted_at IS NULL)
     */
    async findAllActive() {
        const results = this.db.prepare(`
      SELECT 
        vault_id,
        agent_id,
        key,
        value,
        immutable,
        version,
        previous_version_id,
        admin_override,
        deleted_at,
        origin_source,
        created_at,
        updated_at
      FROM knowledge_vault
      WHERE deleted_at IS NULL
      ORDER BY agent_id, key, version DESC
    `).all();
        // 각 (agent_id, key) 조합별 최신 버전만 반환
        const latestByKey = new Map();
        for (const result of results) {
            const mapKey = `${result.agent_id}:${result.key}`;
            const existing = latestByKey.get(mapKey);
            if (!existing || result.version > existing.version) {
                latestByKey.set(mapKey, result);
            }
        }
        return Array.from(latestByKey.values()).map(result => ({
            ...result,
            immutable: Boolean(result.immutable),
            admin_override: Boolean(result.admin_override)
        }));
    }
    /**
     * Knowledge Vault 개수 조회
     */
    async count(agent_id, activeOnly = true) {
        const whereClause = agent_id
            ? activeOnly
                ? 'WHERE agent_id = ? AND deleted_at IS NULL'
                : 'WHERE agent_id = ?'
            : activeOnly
                ? 'WHERE deleted_at IS NULL'
                : '';
        const query = `SELECT COUNT(*) as count FROM knowledge_vault ${whereClause}`;
        const result = agent_id
            ? this.db.prepare(query).get(agent_id)
            : this.db.prepare(query).get();
        return result.count;
    }
    /**
     * 다음 버전 번호 조회 (agent_id, key 기준)
     */
    async getNextVersion(agent_id, key) {
        const result = this.db.prepare(`
      SELECT MAX(version) as max_version
      FROM knowledge_vault
      WHERE agent_id = ? AND key = ?
    `).get(agent_id, key);
        return (result?.max_version ?? 0) + 1;
    }
}
//# sourceMappingURL=knowledge-vault-repository-sqlite.impl.js.map