const express = require('express');
const blockService = require('../services/blockService');

const router = express.Router();

router.use((req, res, next) => {
  res.set('X-PLAI-Ledger-Role', 'legacy-read-only-archive');
  next();
});

router.get('/', (req, res) => {
  res.json({
    ok: true,
    stats: blockService.getBlockStats(),
    blocks: blockService.listBlocks()
  });
});

router.get('/stats/summary', (req, res) => {
  res.json({
    ok: true,
    stats: blockService.getBlockStats(),
    chain: blockService.verifyBlockChain()
  });
});

router.get('/pending/proofs', (req, res) => {
  res.json({
    ok: true,
    proofs: blockService.getPendingProofs(Number(req.query.limit || 100))
  });
});

router.post('/mine', (req, res) => {
  const result = blockService.minePendingProofs({
    limit: req.body?.limit || req.query?.limit || 100,
    reason: req.body?.reason || 'manual-api'
  });

  res.status(result.created ? 201 : 200).json({
    ok: true,
    ...result
  });
});

router.get('/verify', (req, res) => {
  res.json({
    ok: true,
    chain: blockService.verifyBlockChain()
  });
});

router.get('/validators/eligible', (req, res) => {
  res.json({
    ok: true,
    validators: blockService.getEligibleValidators()
  });
});

router.get('/:blockId/votes', (req, res) => {
  const block = blockService.getBlock(req.params.blockId);

  if (!block) {
    return res.status(404).json({
      ok: false,
      error: 'BLOCK_NOT_FOUND'
    });
  }

  res.json({
    ok: true,
    block,
    votes: blockService.getVotesForBlock(block.id)
  });
});

router.post('/:blockId/assign-validators', (req, res) => {
  const result = blockService.assignValidators(req.params.blockId, {
    limit: req.body?.limit || req.query?.limit
  });

  if (!result) {
    return res.status(404).json({
      ok: false,
      error: 'BLOCK_NOT_FOUND'
    });
  }

  res.json({
    ok: true,
    ...result
  });
});

router.post('/:blockId/vote', async (req, res, next) => {
  try {
    const result = await blockService.voteBlock(req.params.blockId, {
      validatorNodeId: req.body?.validatorNodeId,
      vote: req.body?.vote,
      reason: req.body?.reason,
      signature: req.body?.signature,
      metadata: req.body?.metadata || {}
    });

    if (!result) {
      return res.status(404).json({
        ok: false,
        error: 'BLOCK_NOT_FOUND'
      });
    }

    res.json({
      ok: true,
      ...result
    });
  } catch (err) {
    next(err);
  }
});

router.post('/:blockId/mock-finalize', async (req, res, next) => {
  try {
    const result = await blockService.mockFinalizeBlock(req.params.blockId);

    if (!result) {
      return res.status(404).json({
        ok: false,
        error: 'BLOCK_NOT_FOUND'
      });
    }

    res.json({
      ok: true,
      ...result
    });
  } catch (err) {
    next(err);
  }
});

router.get('/:blockId', (req, res) => {
  const block = blockService.getBlock(req.params.blockId);

  if (!block) {
    return res.status(404).json({
      ok: false,
      error: 'BLOCK_NOT_FOUND'
    });
  }

  return res.json({
    ok: true,
    block
  });
});

module.exports = router;
