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

const router = express.Router();

router.get('/', (req, res) => {
  res.json({
    ok: true,
    stats: backupIndexService.getBackupStats(),
    backups: backupIndexService.listBackups()
  });
});

router.get('/chunks', (req, res) => {
  res.json({
    ok: true,
    chunks: backupIndexService.listChunks()
  });
});

router.get('/:backupId', (req, res) => {
  const backup = backupIndexService.getBackup(req.params.backupId);
  if (!backup) {
    return res.status(404).json({ ok: false, error: 'BACKUP_NOT_FOUND' });
  }

  return res.json({
    ok: true,
    backup,
    chunks: backupIndexService.getBackupChunks(backup.backupId)
  });
});

router.post('/', requireServiceAuth, async (req, res, next) => {
  try {
    const result = await backupIndexService.createBackup(req.body);
    res.status(result.created ? 201 : 200).json({
      ok: true,
      created: result.created,
      serviceIdentity: req.serviceIdentity,
      backup: result.backup
    });
  } catch (err) {
    next(err);
  }
});

router.post('/:backupId/chunks', requireServiceAuth, async (req, res, next) => {
  try {
    const result = await backupIndexService.upsertChunk({
      ...req.body,
      backupId: req.params.backupId
    });

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

module.exports = router;
