/**
 * @swagger
 * tags:
 *   name: Ledger
 *   description: Global Ledger System - Double-entry and multi-entry ledger operations
 */

import { Router } from 'express';
import { zeroTrustAuthMiddleware } from '@/integration/api-gateway/middleware/auth.middleware';
import { ledgerService } from './ledger.service';
import { ledgerLifecycleService } from './ledger-lifecycle.service';

const router = Router();

/**
 * @swagger
 * /api/ledger/entries:
 *   post:
 *     summary: Create a ledger entry
 *     description: Post a double-entry or multi-entry transaction to the ledger
 *     tags: [Ledger]
 *     security:
 *       - SovereignToken: []
 *     requestBody:
 *       required: true
 *       content:
 *         application/json:
 *           schema:
 *             type: object
 *             required:
 *               - ledgerId
 *               - debitAccountId
 *               - creditAccountId
 *               - amount
 *               - currencyCode
 *               - transactionType
 *               - referenceId
 *             properties:
 *               ledgerId:
 *                 type: string
 *                 description: Ledger identifier (MASTER, SOVEREIGN, etc.)
 *                 example: "MASTER"
 *               debitAccountId:
 *                 type: string
 *                 description: Debit account ID
 *               creditAccountId:
 *                 type: string
 *                 description: Credit account ID
 *               amount:
 *                 type: string
 *                 description: Transaction amount (decimal as string)
 *                 example: "1000.00"
 *               currencyCode:
 *                 type: string
 *                 description: ISO 4217 currency code
 *                 example: "USD"
 *               assetType:
 *                 type: string
 *                 enum: [fiat, cbdc, commodity, security]
 *                 default: fiat
 *               transactionType:
 *                 type: string
 *                 enum: [TYPE_A, TYPE_B, TYPE_C, TYPE_D, TYPE_E, TYPE_F, TYPE_G]
 *                 description: Transaction type classification
 *               referenceId:
 *                 type: string
 *                 description: External reference ID
 *               fxRate:
 *                 type: string
 *                 description: FX rate if applicable
 *               metadata:
 *                 type: object
 *                 description: Additional transaction metadata
 *     responses:
 *       200:
 *         description: Ledger entry created successfully
 *         content:
 *           application/json:
 *             schema:
 *               type: object
 *               properties:
 *                 success:
 *                   type: boolean
 *                 data:
 *                   type: object
 *                   properties:
 *                     entryIds:
 *                       type: array
 *                       items:
 *                         type: string
 *                     blockHash:
 *                       type: string
 *                     status:
 *                       type: string
 *       400:
 *         description: Validation error
 *       401:
 *         description: Unauthorized
 *       500:
 *         description: Internal server error
 */
router.post('/entries', zeroTrustAuthMiddleware, async (req, res, next) => {
  try {
    const result = await ledgerService.postEntry({
      ledgerId: req.body.ledgerId,
      debitAccountId: req.body.debitAccountId,
      creditAccountId: req.body.creditAccountId,
      amount: req.body.amount,
      currencyCode: req.body.currencyCode,
      assetType: req.body.assetType || 'fiat',
      transactionType: req.body.transactionType,
      referenceId: req.body.referenceId,
      fxRate: req.body.fxRate,
      metadata: req.body.metadata,
    });

    res.json({
      success: true,
      data: result,
      timestamp: new Date(),
    });
  } catch (error) {
      return next(error);
  }
});

/**
 * @swagger
 * /api/ledger/entries/{id}:
 *   get:
 *     summary: Get ledger entry by ID
 *     description: Retrieve a specific ledger entry
 *     tags: [Ledger]
 *     security:
 *       - SovereignToken: []
 *     parameters:
 *       - in: path
 *         name: id
 *         required: true
 *         schema:
 *           type: string
 *         description: Ledger entry ID
 *     responses:
 *       200:
 *         description: Ledger entry retrieved
 *       404:
 *         description: Entry not found
 */
router.get('/entries/:id', zeroTrustAuthMiddleware, async (req, res, next) => {
  try {
    const entries = await ledgerService.getEntriesByReference(req.params.id);
    if (entries.length === 0) {
      return res.status(404).json({
        success: false,
        error: { code: 'NOT_FOUND', message: 'Ledger entry not found' },
        timestamp: new Date(),
      });
    }

    res.json({
      success: true,
      data: entries[0],
      timestamp: new Date(),
    });
  } catch (error) {
      return next(error);
  }
});

export default router;

