import { Router } from 'express';
import { v4 as uuidv4 } from 'uuid';
import { gatewayApiService } from '../edge/api-gateway.service';
import { eventStoreService } from '../data/event-store.service';
import { gatewayInboxService } from '../control/inbox.service';

const router = Router();

// Attach correlation middleware for all gateway routes
router.use(gatewayApiService.correlationMiddleware.bind(gatewayApiService));

/**
 * POST /api/v1/gateway/instructions
 * Scaffold endpoint to accept a canonical instruction and emit an event.
 */
router.post('/instructions', async (req, res, next) => {
	try {
		const txnId = req.body?.txnId || `TXN-${uuidv4()}`;
		const correlationId = (req as any).correlationId || `CORR-${uuidv4()}`;

		// Ingest → Inbox (dedup)
		await gatewayInboxService.accept({
			rail: 'CANONICAL',
			payload: JSON.stringify(req.body || {}),
		});

		// Emit InstructionReceived
		eventStoreService.append({
			eventId: `EVT-${uuidv4()}`,
			txnId,
			eventType: 'InstructionReceived',
			eventTime: new Date().toISOString(),
			producerService: 'dbis.edge.api-gateway',
			payload: { correlationId, instruction: req.body || {} },
		});

		return res.status(202).json({ txnId, correlationId, status: 'RECEIVED' });
	} catch (error) {
		return next(error);
	}
});

/**
 * GET /api/v1/gateway/events/replay
 * Simple replay endpoint for canonical events (scaffold).
 */
router.get('/events/replay', async (req, res, next) => {
	try {
		const from = Number(req.query.from || 0);
		const events = eventStoreService.replay(from);
		return res.json({ count: events.length, events });
	} catch (error) {
		return next(error);
	}
});

export default router;

