/**
 * Central audit client for orchestration portal
 * Sends admin action audit entries to dbis_core Admin Central API when configured.
 * Set DBIS_CENTRAL_URL and ADMIN_CENTRAL_API_KEY to enable.
 */

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

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

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

/**
 * Append an audit entry to the central audit log (dbis_core).
 * No-op if DBIS_CENTRAL_URL or ADMIN_CENTRAL_API_KEY is not set.
 */
export async function appendAudit(payload: AuditPayload): 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,
        project: 'smom-dbis-138',
        service: SERVICE_NAME,
        outcome: payload.outcome ?? 'success',
        metadata: payload.metadata,
        ipAddress: payload.ipAddress,
        userAgent: payload.userAgent,
      }),
    });
    if (!res.ok) {
      console.warn(`[central-audit] POST audit failed: ${res.status} ${await res.text()}`);
    }
  } catch (err) {
    console.warn('[central-audit] append failed:', err instanceof Error ? err.message : err);
  }
}

/**
 * Check if subject has permission via central API.
 * Returns false if not configured or on error.
 */
export async function checkPermission(
  subjectId: string,
  permission: string
): Promise<boolean> {
  if (!isConfigured()) return false;

  try {
    const res = await fetch(`${DBIS_CENTRAL_URL}/api/admin/central/permission-check`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'X-Admin-Central-Key': ADMIN_CENTRAL_API_KEY!,
      },
      body: JSON.stringify({ subjectId, permission }),
    });
    if (!res.ok) return false;
    const data = (await res.json()) as { success?: boolean; allowed?: boolean };
    return Boolean(data?.allowed);
  } catch {
    return false;
  }
}
