// FreeScout customer-service report router. Read-only — authenticated-only is
// sufficient (same stance as Google/Typeform); no requirePermission() gate.

import express from 'express';
import { FreescoutService } from '../../services/freescout/freescout.service.js';

const ALLOWED_DAYS = new Set([7, 14, 30, 90, 180, 365]);

export function createFreescoutRouter({ redis, freescoutPool, phonePool }) {
  const router = express.Router();
  const freescout = new FreescoutService(redis, freescoutPool, phonePool);

  router.get('/report', async (req, res) => {
    const days = Number(req.query.days) || 30;
    if (!ALLOWED_DAYS.has(days)) {
      return res.status(400).json({
        error: 'Invalid days parameter',
        details: `days must be one of ${[...ALLOWED_DAYS].join(', ')}`,
      });
    }
    try {
      res.json(await freescout.getReport(days));
    } catch (error) {
      console.error('FreeScout report error:', { days, error: error.message });
      res.status(500).json({ error: 'Failed to build FreeScout report', details: error.message });
    }
  });

  return router;
}
