const express = require('express');
const { readBoxes, writeBoxes } = require('../lib/boxesStore');

const router = express.Router();
const EDITOR_CODE = process.env.BOX_EDITOR_CODE || process.env.ADMIN_CODE || '1234';

function requireEditorCode(req, res, next) {
  const code = req.headers['x-editor-code'] || req.body.editorCode || req.query.editorCode;
  if (code !== EDITOR_CODE) {
    return res.status(401).json({ success: false, message: 'Invalid editor code' });
  }
  next();
}

router.get('/', (req, res) => {
  res.json({
    success: true,
    boxes: readBoxes(),
    file: 'backend/data/boxes.json',
  });
});

router.put('/', requireEditorCode, (req, res) => {
  const boxes = Array.isArray(req.body.boxes) ? req.body.boxes : [];
  if (boxes.length !== 8) {
    return res.status(400).json({ success: false, message: 'Exactly 8 boxes are required.' });
  }

  const savedBoxes = writeBoxes(boxes);
  res.json({
    success: true,
    message: 'Box data saved successfully.',
    boxes: savedBoxes,
    file: 'backend/data/boxes.json',
  });
});

module.exports = router;
