/**
 * API Route: Generate demand signal
 * POST /api/demand/signal
 */

import type { NextApiRequest, NextApiResponse } from 'next';
import { getDemandForecaster } from '../../../lib/demand/forecaster';

export default async function handler(
  req: NextApiRequest,
  res: NextApiResponse
) {
  if (req.method !== 'POST') {
    return res.status(405).json({ success: false, error: 'Method not allowed' });
  }

  try {
    const {
      centerLat,
      centerLon,
      radiusKm,
      regionName,
      season
    } = req.body;

    // Validate required fields
    if (centerLat === undefined || centerLon === undefined || !radiusKm || !regionName || !season) {
      return res.status(400).json({
        success: false,
        error: 'Missing required fields: centerLat, centerLon, radiusKm, regionName, season'
      });
    }

    // Validate season
    const validSeasons = ['spring', 'summer', 'fall', 'winter'];
    if (!validSeasons.includes(season)) {
      return res.status(400).json({
        success: false,
        error: 'Invalid season. Must be one of: spring, summer, fall, winter'
      });
    }

    const forecaster = getDemandForecaster();
    const signal = forecaster.generateDemandSignal(
      centerLat,
      centerLon,
      radiusKm,
      regionName,
      season
    );

    res.status(201).json({
      success: true,
      data: signal
    });
  } catch (error: any) {
    console.error('Error generating demand signal:', error);
    res.status(500).json({ success: false, error: error.message || 'Internal server error' });
  }
}
