// AS4 Settlement API Routes

import { Router } from 'express';
import { instructionIntakeService } from './instruction-intake.service';
import { postingEngineService } from './posting-engine.service';
import { reconciliationService } from './reconciliation.service';
import { as4GatewayService } from '../as4/as4-gateway.service';

const router = Router();

/**
 * POST /api/v1/as4/settlement/instructions
 * Submit settlement instruction
 */
router.post('/instructions', async (req, res, next) => {
  try {
    const as4Message = req.body.message;
    const fromMemberId = req.body.fromMemberId;
    const payloadHash = req.body.payloadHash;
    const signatureEvidence = req.body.signatureEvidence;
    const as4ReceiptEvidence = req.body.as4ReceiptEvidence;

    const result = await instructionIntakeService.processInstruction(
      as4Message,
      fromMemberId,
      payloadHash,
      signatureEvidence,
      as4ReceiptEvidence
    );

    if (result.status === 'ACCEPTED') {
      // Route to settlement core for processing
      await as4GatewayService.routeToSettlementCore(result.instructionId, JSON.stringify(as4Message));
      res.status(202).json(result);
    } else {
      res.status(400).json(result);
    }
  } catch (error) {
    next(error);
  }
});

/**
 * GET /api/v1/as4/settlement/instructions/:instructionId
 * Get instruction status
 */
router.get('/instructions/:instructionId', async (req, res, next) => {
  try {
    const { instructionId } = req.params;
    const fromMemberId = req.query.fromMemberId as string;

    if (!fromMemberId) {
      return res.status(400).json({
        error: 'VALIDATION_ERROR',
        message: 'fromMemberId is required',
      });
    }

    const instruction = await instructionIntakeService.getInstruction(instructionId, fromMemberId);
    if (!instruction) {
      return res.status(404).json({
        error: 'NOT_FOUND',
        message: `Instruction ${instructionId} not found`,
      });
    }

    res.json(instruction);
  } catch (error) {
    next(error);
  }
});

/**
 * GET /api/v1/as4/settlement/postings/:postingId
 * Get posting status
 */
router.get('/postings/:postingId', async (req, res, next) => {
  try {
    const { postingId } = req.params;
    const status = await postingEngineService.getPostingStatus(postingId);

    if (!status) {
      return res.status(404).json({
        error: 'NOT_FOUND',
        message: `Posting ${postingId} not found`,
      });
    }

    res.json(status);
  } catch (error) {
    next(error);
  }
});

/**
 * GET /api/v1/as4/settlement/statements
 * Generate statement
 */
router.get('/statements', async (req, res, next) => {
  try {
    const memberId = req.query.memberId as string;
    const accountId = req.query.accountId as string;
    const startDate = new Date(req.query.startDate as string);
    const endDate = new Date(req.query.endDate as string);

    if (!memberId || !accountId) {
      return res.status(400).json({
        error: 'VALIDATION_ERROR',
        message: 'memberId and accountId are required',
      });
    }

    const statement = await reconciliationService.generateStatement(
      memberId,
      accountId,
      startDate,
      endDate
    );

    res.json(statement);
  } catch (error) {
    next(error);
  }
});

/**
 * GET /api/v1/as4/settlement/audit/:instructionId
 * Export audit trail
 */
router.get('/audit/:instructionId', async (req, res, next) => {
  try {
    const { instructionId } = req.params;
    const fromMemberId = req.query.fromMemberId as string;

    if (!fromMemberId) {
      return res.status(400).json({
        error: 'VALIDATION_ERROR',
        message: 'fromMemberId is required',
      });
    }

    const auditTrail = await reconciliationService.exportAuditTrail(instructionId, fromMemberId);
    if (!auditTrail) {
      return res.status(404).json({
        error: 'NOT_FOUND',
        message: `Instruction ${instructionId} not found`,
      });
    }

    res.json(auditTrail);
  } catch (error) {
    next(error);
  }
});

export default router;
