import { createHash } from 'crypto';
import { logger } from '@/infrastructure/monitoring/logger';

/**
 * dbis.control.inbox
 * Dedup service for inbound traffic, enabling exactly-once effects.
 */
export class GatewayInboxService {
	generateFingerprint(input: { rail: string; payload: string | Buffer; railMsgId?: string }): string {
		const h = createHash('sha256');
		h.update(typeof input.payload === 'string' ? input.payload : input.payload.toString('utf-8'));
		h.update(input.rail);
		if (input.railMsgId) h.update(input.railMsgId);
		return h.digest('hex');
	}

	async accept(params: { rail: string; payload: string | Buffer; railMsgId?: string }): Promise<{
		status: 'InboundAccepted' | 'InboundDuplicate';
		fingerprint: string;
	}> {
		const fingerprint = this.generateFingerprint(params);
		// NOTE: Persist to gateway_inbox via API layer/DAO (omitted for brevity)
		logger.info('GatewayInboxService.accept', { rail: params.rail, fingerprint, railMsgId: params.railMsgId });
		// For scaffolding, always accept
		return { status: 'InboundAccepted', fingerprint };
	}
}

export const gatewayInboxService = new GatewayInboxService();

