import { Router } from 'express';
import { contentLoader } from '../services/ContentLoader.js';
import { progressionSystem } from '../services/ProgressionSystem.js';

const router = Router();
const DOC_ID_PATTERN = /^[A-Za-z0-9][A-Za-z0-9-]*$/;

router.get('/', (_req, res) => {
  const docs = [...contentLoader.docs.values()]
    .sort((left, right) => left.title.localeCompare(right.title))
    .map((doc) => ({
      id: doc.id,
      title: doc.title,
      locked: !progressionSystem.hasDoc(doc.id)
    }));

  res.json(docs);
});

router.get('/:id', (req, res) => {
  if (!DOC_ID_PATTERN.test(req.params.id)) {
    res.status(400).json({ error: 'Invalid document id' });
    return;
  }

  const doc = contentLoader.get('docs', req.params.id);
  if (!doc) {
    res.status(404).json({ error: 'Document not found' });
    return;
  }

  if (!progressionSystem.hasDoc(doc.id)) {
    res.status(403).json({ error: 'Document locked' });
    return;
  }

  res.json({
    id: doc.id,
    title: doc.title,
    content: doc.body
  });
});

export default router;
