import { Router } from 'express';
import { getContent, updateSection, updateAllContent } from '../db.js';
import { requireAuth } from '../auth.js';
import seedContent from '../seed/default-content.json' with { type: 'json' };

const VALID_SECTIONS = Object.keys(seedContent);

const router = Router();

router.get('/', (_req, res) => {
  const { content, updatedAt } = getContent();
  res.json({ ...content, _updatedAt: updatedAt });
});

router.put('/', requireAuth, (req, res) => {
  const { _updatedAt, ...content } = req.body;
  const updatedAt = updateAllContent(content);
  res.json({ message: 'Content updated', updatedAt });
});

router.put('/:section', requireAuth, (req, res) => {
  const { section } = req.params;
  if (!VALID_SECTIONS.includes(section)) {
    return res.status(404).json({ error: `Unknown section: ${section}`, code: 'NOT_FOUND' });
  }
  const updatedAt = updateSection(section, req.body);
  res.json({ message: `${section} updated`, updatedAt });
});

export default router;
