const express = require('express');
const { requireAuth } = require('../middleware/auth');
const { checkGracePeriod } = require('../middleware/gracePeriod');
const { scanLimit } = require('../middleware/scanLimit');
const { scanParlay } = require('../services/parlayScanService');

const router = express.Router();

const VALID_STAT_TYPES = new Set([
  // NBA / WNBA
  'points', 'rebounds', 'assists', 'threes', 'blocks',
  'steals', 'pra', 'turnovers',
  // Soccer (Session 7j)
  'goals', 'shots_on_target', 'shots', 'tackles', 'cards',
  'corners', 'saves', 'goals_conceded', 'passes', 'clean_sheet',
  // MLB (Session 41) — mirrors src/routes/analyze.js + python validation.
  'strikeouts', 'hits', 'home_runs', 'rbi', 'total_bases',
  'walks', 'runs', 'earned_runs', 'innings_pitched',
  'hits_allowed', 'stolen_bases',
  // Session 56 audit — keep in sync with analyze.js + validation.py.
  'doubles', 'outs',
]);
const VALID_DIRECTIONS = new Set(['over', 'under']);

function validateLegs(legs) {
  if (!Array.isArray(legs) || legs.length < 2) {
    return 'legs array is required with at least 2 props';
  }
  if (legs.length > 12) {
    return 'max_legs_exceeded';
  }
  for (let i = 0; i < legs.length; i++) {
    const leg = legs[i];
    if (!leg.player) return `leg ${i}: player is required`;
    if (!leg.stat_type) return `leg ${i}: stat_type is required`;
    if (leg.stat_type && !VALID_STAT_TYPES.has(leg.stat_type)) {
      return `leg ${i}: Invalid stat_type: ${leg.stat_type}`;
    }
    if (leg.line == null) return `leg ${i}: line is required`;
    if (!leg.direction) return `leg ${i}: direction is required`;
    if (leg.direction && !VALID_DIRECTIONS.has(leg.direction)) {
      return `leg ${i}: Invalid direction: ${leg.direction}`;
    }
  }
  return null;
}

// requireAuth → checkGracePeriod → scanLimit ordering matters:
// requireAuth populates req.user; checkGracePeriod may downgrade
// req.user.tier; scanLimit reads tier off req.user to pick the
// per-tier quota. If grace check ran AFTER scanLimit, a just-
// expired Desk user would get unlimited quota for one final scan.
router.post('/parlay', requireAuth, checkGracePeriod, scanLimit(), async (req, res) => {
  const { legs } = req.body;

  const validationError = validateLegs(legs);
  if (validationError === 'max_legs_exceeded') {
    return res.status(422).json({ error: 'Maximum 12 legs per parlay' });
  }
  if (validationError) {
    return res.status(400).json({ error: validationError });
  }

  try {
    const result = await scanParlay(req.user, legs);

    if (result.blocked) {
      return res.status(403).json({
        error: 'scan_limit_reached',
        scan_count: result.scan_count,
        scans_remaining: result.scans_remaining,
        upgrade_pitch: result.upgrade_pitch,
      });
    }

    return res.json(result);
  } catch (err) {
    console.error('[VYNDR] Scan error:', err.message);
    return res.status(503).json({ error: 'Scan service temporarily unavailable' });
  }
});

module.exports = router;
