/**
 * Central audit client for token-aggregation admin actions
 * Sends audit entries to dbis_core Admin Central API when DBIS_CENTRAL_URL and ADMIN_CENTRAL_API_KEY are set.
 */

import { logger } from '../utils/logger';

const DBIS_CENTRAL_URL = process.env.DBIS_CENTRAL_URL?.replace(/\/$/, '');
const ADMIN_CENTRAL_API_KEY = process.env.ADMIN_CENTRAL_API_KEY;
const SERVICE_NAME = 'token_aggregation';

function isConfigured(): boolean {
  return Boolean(DBIS_CENTRAL_URL && ADMIN_CENTRAL_API_KEY);
}

export interface CentralAuditPayload {
  employeeId: string;
  action: string;
  permission: string;
  resourceType: string;
  resourceId?: string | null;
  outcome?: string;
  metadata?: Record<string, unknown>;
  ipAddress?: string;
  userAgent?: string;
}

export async function appendCentralAudit(payload: CentralAuditPayload): Promise<void> {
  if (!isConfigured()) return;

  try {
    const res = await fetch(`${DBIS_CENTRAL_URL}/api/admin/central/audit`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'X-Admin-Central-Key': ADMIN_CENTRAL_API_KEY!,
      },
      body: JSON.stringify({
        employeeId: payload.employeeId,
        action: payload.action,
        permission: payload.permission ?? 'admin:action',
        resourceType: payload.resourceType,
        resourceId: payload.resourceId ?? undefined,
        project: 'smom-dbis-138',
        service: SERVICE_NAME,
        outcome: payload.outcome ?? 'success',
        metadata: payload.metadata,
        ipAddress: payload.ipAddress,
        userAgent: payload.userAgent,
      }),
    });
    if (!res.ok) {
      logger.warn(`[central-audit] POST failed: ${res.status} ${await res.text()}`);
    }
  } catch (err) {
    logger.warn('[central-audit] append failed:', err instanceof Error ? err.message : err);
  }
}
