import fs from 'fs';
import { logger } from '@/infrastructure/monitoring/logger';
import type { ErrorCode } from '@/shared/types';

export type GatewayRailsAuditDecision = 'allow' | 'deny';

export interface GatewayRailsAuditRecord {
	decision: GatewayRailsAuditDecision;
	tenantId: string;
	path: string;
	method: string;
	adapterId?: string;
	errorCode?: ErrorCode | string;
	correlationId?: string;
	ingress?: string;
}

/**
 * Structured audit for SolaceNet gateway rail capability checks (PG-GW-W03).
 * Always logs to Winston; optionally appends one NDJSON line per event when
 * SOLACENET_GATEWAY_AUDIT_LOG_PATH is set (operator-owned directory, rotation).
 */
export function recordGatewayRailsAudit(record: GatewayRailsAuditRecord): void {
	const payload = {
		auditType: 'gateway_rails_enforcement',
		ts: new Date().toISOString(),
		...record,
	};
	logger.info('Gateway rails enforcement audit', payload);

	const path = process.env.SOLACENET_GATEWAY_AUDIT_LOG_PATH?.trim();
	if (!path) return;

	try {
		fs.appendFileSync(path, `${JSON.stringify(payload)}\n`, { encoding: 'utf8', flag: 'a' });
	} catch (err) {
		logger.warn('SOLACENET_GATEWAY_AUDIT_LOG_PATH append failed', {
			path,
			error: err instanceof Error ? err.message : String(err),
		});
	}
}
