/**
 * API Route: Get demand forecast
 * GET /api/demand/forecast
 */

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

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

  try {
    const { regionName, forecastWeeks } = req.query;

    // Validate required fields
    if (!regionName) {
      return res.status(400).json({
        success: false,
        error: 'Missing required query parameter: regionName'
      });
    }

    const weeks = forecastWeeks ? parseInt(forecastWeeks as string, 10) : 12;

    if (isNaN(weeks) || weeks < 1 || weeks > 52) {
      return res.status(400).json({
        success: false,
        error: 'forecastWeeks must be a number between 1 and 52'
      });
    }

    const forecaster = getDemandForecaster();
    const forecast = forecaster.generateForecast(regionName as string, weeks);

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