// Meta-Ledger System (MLS) - API Routes

import { Router } from 'express';
import { mlsService } from './mls.service';
import { LedgerType } from './types';

const router = Router();

/**
 * @swagger
 * tags:
 *   name: Meta-Ledger
 *   description: Meta-Ledger Synchronization System (MLS)
 */

/**
 * @swagger
 * /api/mls/register:
 *   post:
 *     summary: Register a ledger for synchronization
 *     description: Register a ledger with the Meta-Ledger Synchronization System
 *     tags: [Meta-Ledger]
 *     security:
 *       - SovereignToken: []
 *     requestBody:
 *       required: true
 *       content:
 *         application/json:
 *           schema:
 *             type: object
 *             required:
 *               - ledgerId
 *               - ledgerType
 *             properties:
 *               ledgerId:
 *                 type: string
 *               ledgerType:
 *                 type: string
 *     responses:
 *       200:
 *         description: Ledger registered successfully
 */
router.post('/register', async (req, res) => {
  try {
    await mlsService.registerLedger(req.body);

    res.json({ success: true });
  } catch (error) {
    res.status(500).json({ error: (error as Error).message });
  }
});

/**
 * POST /api/mls/synchronize
 * Synchronize a ledger state
 */
router.post('/synchronize', async (req, res) => {
  try {
    const ledgerState = await mlsService.synchronizeLedger(req.body);

    res.json(ledgerState);
  } catch (error) {
    res.status(500).json({ error: (error as Error).message });
  }
});

/**
 * POST /api/mls/commit
 * Commit meta-state for current epoch
 */
router.post('/commit', async (req, res) => {
  try {
    const result = await mlsService.commitMetaState();

    res.json(result);
  } catch (error) {
    res.status(500).json({ error: (error as Error).message });
  }
});

/**
 * GET /api/mls/state
 * Get current meta-state
 */
router.get('/state', async (req, res) => {
  try {
    const metaState = await mlsService.getCurrentMetaState();

    if (!metaState) {
      return res.status(404).json({ error: 'No meta-state available' });
    }

    res.json(metaState);
  } catch (error) {
    res.status(500).json({ error: (error as Error).message });
  }
});

/**
 * POST /api/mls/configure
 * Configure synchronization settings
 */
router.post('/configure', async (req, res) => {
  try {
    mlsService.configure(req.body);

    res.json({ success: true });
  } catch (error) {
    res.status(500).json({ error: (error as Error).message });
  }
});

export default router;

