const express = require('express');
const proofLedgerService = require('../services/proofLedgerService');
const { requireServiceAuth } = require('../middleware/serviceAuth');

const router = express.Router();

router.get('/', (req, res) => {
  res.json({
    ok: true,
    proofs: proofLedgerService.listProofs()
  });
});

router.get('/stats/summary', (req, res) => {
  res.json({
    ok: true,
    stats: proofLedgerService.getProofStats()
  });
});

router.get('/:proofId', (req, res) => {
  const proof = proofLedgerService.getProof(req.params.proofId);

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

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

router.post('/', requireServiceAuth, async (req, res, next) => {
  try {
    const result = await proofLedgerService.createProof(req.body);

    res.status(result.created ? 201 : 200).json({
      ok: true,
      created: result.created,
      serviceIdentity: req.serviceIdentity,
      proof: result.proof
    });
  } catch (err) {
    next(err);
  }
});

module.exports = router;
