/**
 * jobs/evidenceRetention.js
 *
 * Once a day, prune `case_discovery_scans` rows older than
 * NCII_EVIDENCE_RETENTION_DAYS (default 90) AND the matching audit
 * JSON files in data/evidence/case_<id>/.
 *
 * Why: each scan writes one JSON, scans run for every case, and the
 * table + filesystem grow forever. 1000 cases × 10 scans = 10,000
 * files. Most of that is noise; operators only ever look at the most
 * recent scan per case.
 *
 * If the operator ever needs older evidence (legal hold, dispute), they
 * can re-run a deep discovery scan and the JSON will be regenerated
 * with the same scan_id.
 *
 * Set NCII_EVIDENCE_RETENTION_DAYS=0 to disable.
 */

'use strict';

const fs = require('fs');
const path = require('path');
const { db, logger } = (() => { try { return { db: require('../config/db').db, logger: require('../middleware/logger').logger }; } catch (_) { return { db: require('../config/db').db, logger: console }; } })();

const DEFAULT_DAYS = 90;
let timer = null;

async function tick() {
  const days = parseInt(process.env.NCII_EVIDENCE_RETENTION_DAYS, 10);
  const effective = (Number.isFinite(days) ? days : DEFAULT_DAYS);
  if (effective <= 0) {
    logger.debug && logger.debug('evidenceRetention.disabled');
    return { deleted: 0, reason: 'disabled' };
  }
  const cutoff = Date.now() - effective * 24 * 60 * 60 * 1000;
  // Find rows to delete so we can also clean the JSONs
  const rows = db.prepare(`
    SELECT id, case_id FROM case_discovery_scans
     WHERE created_at < ? AND status IN ('done','failed','cancelled','chain_only')
  `).all(cutoff);
  if (!rows.length) {
    logger.info && logger.info('evidenceRetention.tick', { deleted: 0, cutoff, days: effective });
    return { deleted: 0 };
  }
  // Remove the audit JSONs (best effort; missing files are fine)
  const evidenceRoot = path.join(__dirname, '..', 'data', 'evidence');
  let filesDeleted = 0;
  for (const r of rows) {
    const dir = path.join(evidenceRoot, `case_${r.case_id}`);
    try {
      const files = fs.readdirSync(dir);
      for (const f of files) {
        if (f.startsWith(`scan_${r.id}_`) && f.endsWith('.json')) {
          try { fs.unlinkSync(path.join(dir, f)); filesDeleted++; } catch (_) {}
        }
      }
    } catch (_) { /* dir missing — nothing to clean */ }
  }
  const r = db.prepare(`DELETE FROM case_discovery_scans WHERE created_at < ? AND status IN ('done','failed','cancelled','chain_only')`).run(cutoff);
  logger.info && logger.info('evidenceRetention.tick', { days: effective, cutoff, rows_deleted: r.changes, files_deleted: filesDeleted });
  return { deleted: r.changes, files_deleted: filesDeleted };
}

function start() {
  if (timer) return;
  // Run once on startup (so a fresh restart catches up), then every 24h.
  setTimeout(tick, 30_000);   // 30s after boot
  timer = setInterval(tick, 24 * 60 * 60 * 1000);
  console.log(`[evidenceRetention] started (retention ${process.env.NCII_EVIDENCE_RETENTION_DAYS || DEFAULT_DAYS} days)`);
}

function stop() { if (timer) clearInterval(timer); timer = null; }

module.exports = { start, stop, tick };
