/**
 * jobs/caseDiscoveryWorker.js
 * Polls the case_discovery_scans table for queued/running scans and
 * processes them one at a time (so we don't hammer Scrape.do).
 */

'use strict';

const { db } = require('../config/db');
const deepDiscovery = require('../services/deepDiscovery');

const POLL_MS = parseInt(process.env.CASE_DISCOVERY_POLL_MS, 10) || 4000;
let timer = null;
let busy = false;

async function tick() {
  if (busy) return;
  busy = true;
  try {
    const row = db.prepare(`SELECT * FROM case_discovery_scans WHERE status = 'queued' AND created_at <= ? ORDER BY created_at ASC LIMIT 1`).get(Date.now());
    if (!row) return;
    // Mark running atomically
    const r = db.prepare(`UPDATE case_discovery_scans SET status = 'running', started_at = ?, progress = 'Picked up' WHERE id = ? AND status = 'queued'`).run(Date.now(), row.id);
    if (r.changes === 0) return; // someone else got it
    try {
      // Pass the existing scan id so runCaseScan updates THIS row
      // instead of creating a duplicate scan row.
      await deepDiscovery.runCaseScan(row.case_id, row.user_id, { scanId: row.id });
    } catch (err) {
      console.error('[caseDiscovery] scan', row.id, 'failed:', err);
      db.prepare(`UPDATE case_discovery_scans SET status = 'failed', progress = ?, finished_at = ? WHERE id = ?`)
        .run('Failed: ' + err.message, Date.now(), row.id);
    }
  } finally {
    busy = false;
  }
}

function start() {
  if (timer) return;
  timer = setInterval(tick, POLL_MS);
  setTimeout(tick, 500);
  console.log(`[caseDiscovery] started (poll ${POLL_MS}ms)`);
}

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

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