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

const router = express.Router();

router.get('/', (req, res) => {
  res.json({
    ok: true,
    stats: callbackService.getCallbackStats(),
    callbacks: callbackService.listCallbacks()
  });
});

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

router.post('/:callbackId/retry', async (req, res, next) => {
  try {
    const event = await callbackService.retryCallback(req.params.callbackId);

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

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

router.get('/:callbackId', (req, res) => {
  const event = callbackService.getCallback(req.params.callbackId);

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

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

module.exports = router;
