const { getDatabase } = require('../config/database');
const AuditLog = require('../models/AuditLog');

// DSGVO Art. 5 Abs. 1 lit. e (Speicherbegrenzung) — Daten nur so lange aufbewahren wie nötig.
const PATCH_COMMANDS_RETENTION_DAYS = parseInt(process.env.PATCH_COMMANDS_RETENTION_DAYS || '90', 10);
const AUDIT_LOG_RETENTION_DAYS = parseInt(process.env.AUDIT_LOG_RETENTION_DAYS || '180', 10);

function cleanupPatchCommands() {
    const db = getDatabase();
    const stmt = db.prepare(
        `DELETE FROM patch_commands WHERE created_at < datetime('now', '-' || ? || ' days') AND status IN ('done', 'failed')`
    );
    return stmt.run(PATCH_COMMANDS_RETENTION_DAYS).changes;
}

function runRetentionCleanup() {
    try {
        const patchDeleted = cleanupPatchCommands();
        const auditDeleted = AuditLog.cleanupOld(AUDIT_LOG_RETENTION_DAYS);
        console.log(`[DataRetention] Bereinigt: ${patchDeleted} patch_commands (>${PATCH_COMMANDS_RETENTION_DAYS}d), ${auditDeleted} audit_log Einträge (>${AUDIT_LOG_RETENTION_DAYS}d)`);
    } catch (err) {
        console.error('[DataRetention] Fehler:', err.message);
    }
}

module.exports = { runRetentionCleanup, cleanupPatchCommands };
