'use strict';

/**
 * /api/desk (Session 63 / A1-S4) — Kev's copy-paste arsenal.
 *
 * GET /pack — the assembled daily media pack + DATA BRIEF.
 * Auth: requireAuth + email allowlist (env DESK_OWNERS, comma-separated).
 * Unset allowlist → 403 for everyone (deny by default; the desk is the
 * founder's surface, not a tier feature).
 */

const express = require('express');
const { requireAuth } = require('../middleware/auth');
const { createRateLimit } = require('../middleware/rateLimit');
const { assembleDeskPack } = require('../services/deskService');

const router = express.Router();
router.use(createRateLimit({ windowMs: 60_000, max: 20 }));

function isOwner(req) {
  const owners = String(process.env.DESK_OWNERS || '')
    .split(',').map((s) => s.trim().toLowerCase()).filter(Boolean);
  const email = String(req.user?.email || '').toLowerCase();
  return owners.length > 0 && email && owners.includes(email);
}

router.get('/pack', requireAuth, async (req, res) => {
  if (!isOwner(req)) {
    return res.status(403).json({ error: 'The desk is the publisher’s surface. Set DESK_OWNERS to grant access.' });
  }
  try {
    const pack = await assembleDeskPack();
    res.set('Cache-Control', 'private, max-age=60');
    return res.json(pack);
  } catch (err) {
    console.error('[desk/pack]', err.message);
    return res.status(200).json({ generated_at: null, formats: {}, data_brief: null, error: 'assembly failed' });
  }
});

module.exports = router;
