/**
 * AuditChainVerificationJob — SOC 2 CC7.2 Audit Log Integrity monitoring.
 *
 * Runs on a configurable interval (default: 1 hour) and calls
 * `auditVerificationService.verifyChain()` over the full audit log.
 * Sets the `agentidp_audit_chain_integrity` Prometheus gauge to:
 *   1 — chain is intact (verification passed)
 *   0 — chain break detected (verification failed; possible tampering)
 *
 * The gauge is also reflected in the ComplianceStatusStore as control CC7.2,
 * allowing the GET /compliance/controls endpoint to surface the current state
 * without a real-time database query.
 *
 * Configuration:
 *   AUDIT_CHAIN_VERIFICATION_INTERVAL_MS — interval in milliseconds (default: 3600000 = 1 hour)
 */

import { AuditVerificationService } from '../services/AuditVerificationService.js';
import { auditChainIntegrity } from '../metrics/registry.js';
import { updateControlStatus } from '../services/ComplianceStatusStore.js';

// ============================================================================
// Job
// ============================================================================

/** Default verification interval: 1 hour in milliseconds. */
const DEFAULT_INTERVAL_MS = 3600000;

/**
 * Runs a full audit chain verification and updates the Prometheus gauge
 * and ComplianceStatusStore accordingly.
 *
 * @param auditVerificationService - The service to delegate chain verification to.
 */
async function runChainVerification(
  auditVerificationService: AuditVerificationService,
): Promise<void> {
  try {
    const result = await auditVerificationService.verifyChain();

    if (result.verified) {
      auditChainIntegrity.set(1);
      updateControlStatus('CC7.2', 'passing');
      // eslint-disable-next-line no-console
      console.log(
        `[AuditChainVerificationJob] Chain intact — ${result.checkedCount} event(s) verified.`,
      );
    } else {
      auditChainIntegrity.set(0);
      updateControlStatus('CC7.2', 'failing');
      // eslint-disable-next-line no-console
      console.error(
        `[AuditChainVerificationJob] Chain BROKEN at event ${result.brokenAtEventId ?? 'unknown'} — possible tampering detected!`,
      );
    }
  } catch (err) {
    auditChainIntegrity.set(0);
    updateControlStatus('CC7.2', 'unknown');
    // eslint-disable-next-line no-console
    console.error(
      '[AuditChainVerificationJob] Verification failed:',
      err instanceof Error ? err.message : String(err),
    );
  }
}

/**
 * Starts the audit chain verification background job.
 * Schedules a recurring verification using `setInterval`.
 *
 * @param auditVerificationService - The AuditVerificationService instance to use.
 */
export function startAuditChainVerificationJob(
  auditVerificationService: AuditVerificationService,
): void {
  const intervalMs = parseInt(
    process.env['AUDIT_CHAIN_VERIFICATION_INTERVAL_MS'] ?? String(DEFAULT_INTERVAL_MS),
    10,
  );

  // eslint-disable-next-line no-console
  console.log(
    `[AuditChainVerificationJob] Started — verifying audit chain every ${intervalMs / 1000}s.`,
  );

  setInterval(() => {
    void runChainVerification(auditVerificationService);
  }, intervalMs);
}
