/**
 * ComplianceStatusStore — shared in-memory store for SOC 2 control statuses.
 *
 * This module maintains a module-level Map that background jobs (SecretsRotationJob,
 * AuditChainVerificationJob) write to, and ComplianceController reads from.
 *
 * Using a shared module-level store ensures a single source of truth within a
 * process and avoids introducing a new database dependency for transient status data.
 *
 * SOC 2 controls monitored:
 *   CC6.1 — Encryption at Rest (EncryptionService, AES-256-CBC, Vault-backed keys)
 *   CC6.7 — TLS Enforcement (TLSEnforcementMiddleware, X-Forwarded-Proto)
 *   CC7.2 — Audit Log Integrity (AuditService hash chain, AuditVerificationService)
 *   CC9.2 — Secrets Rotation (SecretsRotationJob, agentidp_credentials_expiring_soon_total)
 *   CC7.1 — Webhook Dead-Letter Monitoring (WebhookDeliveryWorker dead-letter queue)
 */

// ============================================================================
// Types
// ============================================================================

/** Valid status values for a SOC 2 control. */
export type ControlStatus = 'passing' | 'failing' | 'unknown';

/** SOC 2 Trust Services Criteria control identifiers. */
export type ControlId = 'CC6.1' | 'CC6.7' | 'CC7.2' | 'CC9.2' | 'CC7.1';

/** A single SOC 2 control status record. */
export interface IControlStatusRecord {
  id: ControlId;
  name: string;
  status: ControlStatus;
  lastChecked: string;
}

// ============================================================================
// Static control metadata
// ============================================================================

/** Canonical names for each SOC 2 control ID, used by ComplianceController. */
const CONTROL_NAMES: Record<ControlId, string> = {
  'CC6.1': 'Encryption at Rest',
  'CC6.7': 'TLS Enforcement',
  'CC7.2': 'Audit Log Integrity',
  'CC9.2': 'Secrets Rotation',
  'CC7.1': 'Webhook Dead-Letter Monitoring',
};

/** Ordered list of all in-scope control IDs (defines display order in API responses). */
const CONTROL_IDS: ControlId[] = ['CC6.1', 'CC6.7', 'CC7.2', 'CC9.2', 'CC7.1'];

// ============================================================================
// Module-level store
// ============================================================================

/** Internal status storage: control ID → { status, lastChecked ISO string }. */
const statusStore = new Map<ControlId, { status: ControlStatus; lastChecked: string }>(
  CONTROL_IDS.map((id) => [
    id,
    { status: 'unknown', lastChecked: new Date().toISOString() },
  ]),
);

// ============================================================================
// Public API
// ============================================================================

/**
 * Updates the status of a SOC 2 control.
 * Called by background jobs when they complete a check.
 *
 * @param id - The SOC 2 control identifier.
 * @param status - The new status to record.
 */
export function updateControlStatus(id: ControlId, status: ControlStatus): void {
  statusStore.set(id, { status, lastChecked: new Date().toISOString() });
}

/**
 * Returns the current status of all five SOC 2 controls.
 * Called by ComplianceController to build the GET /compliance/controls response.
 *
 * @returns Array of five IControlStatusRecord objects in the canonical display order.
 */
export function getAllControlStatuses(): IControlStatusRecord[] {
  return CONTROL_IDS.map((id) => {
    const stored = statusStore.get(id) ?? { status: 'unknown' as ControlStatus, lastChecked: new Date().toISOString() };
    return {
      id,
      name: CONTROL_NAMES[id],
      status: stored.status,
      lastChecked: stored.lastChecked,
    };
  });
}

/**
 * Returns the current status of a single SOC 2 control.
 *
 * @param id - The SOC 2 control identifier.
 * @returns The IControlStatusRecord for the requested control.
 */
export function getControlStatus(id: ControlId): IControlStatusRecord {
  const stored = statusStore.get(id) ?? { status: 'unknown' as ControlStatus, lastChecked: new Date().toISOString() };
  return {
    id,
    name: CONTROL_NAMES[id],
    status: stored.status,
    lastChecked: stored.lastChecked,
  };
}
