/**
 * API Route: Get planting recommendations
 * GET /api/demand/recommendations
 */

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 {
      growerId,
      latitude,
      longitude,
      radiusKm,
      availableSpaceSqm,
      season
    } = req.query;

    // Validate required fields
    if (!growerId || !latitude || !longitude || !radiusKm || !availableSpaceSqm || !season) {
      return res.status(400).json({
        success: false,
        error: 'Missing required query parameters: growerId, latitude, longitude, radiusKm, availableSpaceSqm, season'
      });
    }

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

    const forecaster = getDemandForecaster();
    const recommendations = forecaster.generatePlantingRecommendations(
      growerId as string,
      parseFloat(latitude as string),
      parseFloat(longitude as string),
      parseFloat(radiusKm as string),
      parseFloat(availableSpaceSqm as string),
      season as 'spring' | 'summer' | 'fall' | 'winter'
    );

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