import { getDatabase, withTransaction } from '../../database/init.js';
import { addMemory } from '../../memory/store.js';
function getPendingQuarantineRow(id) {
    const db = getDatabase();
    const row = db.prepare(`SELECT id, original_title, original_content, project, source_type, source_identifier, reason
       FROM quarantine
      WHERE id = ? AND status = 'pending'`).get(id);
    return row ?? null;
}
function normalizeSourceKind(sourceType) {
    switch (sourceType) {
        case 'cli':
        case 'hook':
        case 'plugin':
        case 'agent':
        case 'import':
        case 'cloud':
        case 'api':
            return sourceType;
        default:
            return 'system';
    }
}
function promoteApprovedQuarantineRow(row, reviewedBy) {
    return addMemory({
        title: row.original_title?.trim() || `Recovered quarantined memory ${row.id}`,
        content: row.original_content,
        project: row.project ?? undefined,
        tags: ['quarantine-approved'],
        metadata: {
            approvedFromQuarantine: true,
            quarantineId: row.id,
            quarantineReason: row.reason ?? null,
            originalSourceType: row.source_type ?? null,
            originalSourceIdentifier: row.source_identifier ?? null,
        },
        captureMethod: 'review',
        reviewedBy,
        sourceKind: normalizeSourceKind(row.source_type),
        source: row.source_type && row.source_identifier
            ? `${row.source_type}:${row.source_identifier}`
            : 'quarantine:review',
    });
}
function markPendingRowReviewed(id, status, reviewedBy) {
    const db = getDatabase();
    const reviewedAt = new Date().toISOString();
    const result = db.prepare('UPDATE quarantine SET status = ?, reviewed_at = ?, reviewed_by = ? WHERE id = ? AND status = ?').run(status, reviewedAt, reviewedBy, id, 'pending');
    if (result.changes === 0) {
        throw new Error('Quarantine entry not found or already reviewed');
    }
}
function approveExistingPendingRow(row, reviewedBy) {
    if (row.source_type === 'memory_file') {
        markPendingRowReviewed(row.id, 'approved', reviewedBy);
        return {
            id: row.id,
            status: 'approved',
        };
    }
    const memory = promoteApprovedQuarantineRow(row, reviewedBy);
    markPendingRowReviewed(row.id, 'approved', reviewedBy);
    return {
        id: row.id,
        status: 'approved',
        memoryId: memory.id,
    };
}
function rejectPendingQuarantineRow(id, reviewedBy) {
    const row = getPendingQuarantineRow(id);
    if (!row) {
        return null;
    }
    markPendingRowReviewed(row.id, 'rejected', reviewedBy);
    return { id, status: 'rejected' };
}
export function approveQuarantineItem(id, reviewedBy = 'dashboard') {
    return withTransaction(() => {
        const row = getPendingQuarantineRow(id);
        if (!row)
            return null;
        return approveExistingPendingRow(row, reviewedBy);
    });
}
export function rejectQuarantineItem(id, reviewedBy = 'dashboard') {
    return withTransaction(() => rejectPendingQuarantineRow(id, reviewedBy));
}
export function approveQuarantineItems(ids, reviewedBy = 'dashboard') {
    return withTransaction(() => {
        const items = [];
        for (const id of ids) {
            const row = getPendingQuarantineRow(id);
            if (!row)
                continue;
            items.push(approveExistingPendingRow(row, reviewedBy));
        }
        return {
            success: true,
            updated: items.length,
            total: ids.length,
            promoted: items.filter((item) => item.memoryId).length,
            items,
        };
    });
}
export function rejectQuarantineItems(ids, reviewedBy = 'dashboard') {
    return withTransaction(() => {
        const items = [];
        for (const id of ids) {
            const result = rejectPendingQuarantineRow(id, reviewedBy);
            if (result)
                items.push(result);
        }
        return {
            success: true,
            updated: items.length,
            total: ids.length,
            promoted: 0,
            items,
        };
    });
}
export function approveQuarantineItemsBySource(sourceIdentifier, reviewedBy = 'dashboard') {
    const db = getDatabase();
    const ids = db.prepare("SELECT id FROM quarantine WHERE status = 'pending' AND source_identifier = ? ORDER BY created_at ASC").all(sourceIdentifier);
    return approveQuarantineItems(ids.map((item) => item.id), reviewedBy);
}
