'use strict';

/**
 * /api/parlay (Session 28)
 *
 * Builder-side parlay math — combined odds, grade, and correlation flags
 * for a set of user-selected legs. Distinct from the existing parlay
 * GRADING path (parlayGrader); this is the lightweight, zero-credit
 * combination used by the live parlay builder.
 *
 *   POST /api/parlay/calculate   { legs: [...] } → combined analysis
 *   POST /api/parlay/suggestions { props, legs?, max? } → suggested combos
 */

const express = require('express');
const parlayService = require('../services/parlayService');
const { createRateLimit } = require('../middleware/rateLimit');

const router = express.Router();
// Session 32 — public throttle. Parlay math is computation-heavy → 30/min.
router.use(createRateLimit({ windowMs: 60_000, max: 30 }));

const MISSION_HEADER = { 'X-VYNDR-Mission': 'Catch the legs that fight each other' };

router.post('/calculate', (req, res) => {
  try {
    const legs = req.body?.legs;
    const result = parlayService.calculateParlay(legs);
    return res.set(MISSION_HEADER).json(result);
  } catch (err) {
    const status = err.statusCode || 400;
    return res.status(status).set(MISSION_HEADER).json({ error: err.message });
  }
});

// POST /api/parlay/grade (Session 50) — the Parlay Lab. Returns
// { combined, correlation, payout, legs }. Public + stateless (the lightweight
// math); the Lab UI is tier-gated on the frontend. 2–6 legs.
router.post('/grade', (req, res) => {
  const legs = req.body?.legs;
  if (!Array.isArray(legs) || legs.length < 2 || legs.length > 6) {
    return res.status(400).set(MISSION_HEADER).json({ error: 'A parlay needs 2–6 legs.' });
  }
  try {
    const betAmount = Number(req.body?.betAmount) || 10;
    return res.set(MISSION_HEADER).json(parlayService.gradeParlay(legs, betAmount));
  } catch (err) {
    return res.status(400).set(MISSION_HEADER).json({ error: err.message });
  }
});

router.post('/suggestions', (req, res) => {
  try {
    const { props, legs, max } = req.body || {};
    const suggestions = parlayService.suggestParlays(props || [], {
      legs: Number(legs) || 3,
      max: Number(max) || 3,
    });
    return res.set(MISSION_HEADER).json({ suggestions });
  } catch (err) {
    return res.status(400).set(MISSION_HEADER).json({ error: err.message });
  }
});

module.exports = router;
