// AS4 Gateway API Routes

import { Router } from 'express';
import { as4GatewayService } from './as4-gateway.service';
import { as4PayloadVaultService } from './as4-payload-vault.service';
import { logger } from '@/infrastructure/monitoring/logger';

const router = Router();

/**
 * POST /api/v1/as4/gateway/messages
 * Receive AS4 message
 */
router.post('/messages', async (req, res, next) => {
  try {
    // Extract TLS certificate fingerprint from request (would be in headers in production)
    const tlsCertFingerprint = req.headers['x-tls-cert-fingerprint'] as string || '';

    const result = await as4GatewayService.processIncomingMessage({
      messageId: req.body.messageId,
      fromMemberId: req.body.fromMemberId,
      toMemberId: req.body.toMemberId,
      businessType: req.body.businessType,
      payload: req.body.payload,
      tlsCertFingerprint,
      properties: req.body.properties,
    });

    if (result.status === 'ACCEPTED') {
      res.status(202).json(result);
    } else {
      res.status(400).json(result);
    }
  } catch (error) {
    next(error);
  }
});

/**
 * GET /api/v1/as4/gateway/vault/:vaultId
 * Retrieve payload from vault
 */
router.get('/vault/:vaultId', async (req, res, next) => {
  try {
    const { vaultId } = req.params;
    const payload = await as4PayloadVaultService.retrievePayload(vaultId);

    if (!payload) {
      return res.status(404).json({
        error: 'NOT_FOUND',
        message: `Vault entry ${vaultId} not found`,
      });
    }

    res.json({ vaultId, payload });
  } catch (error) {
    next(error);
  }
});

/**
 * GET /api/v1/as4/gateway/vault/message/:messageId
 * Retrieve payloads by message ID
 */
router.get('/vault/message/:messageId', async (req, res, next) => {
  try {
    const { messageId } = req.params;
    const payloadType = req.query.payloadType as 'INSTRUCTION' | 'ADVICE' | 'RECEIPT' | undefined;
    const entries = await as4PayloadVaultService.retrievePayloadByMessageId(messageId, payloadType);
    res.json(entries);
  } catch (error) {
    next(error);
  }
});

export default router;
