/**
 * API Route: List growing recipes
 * GET /api/vertical-farm/recipes
 */

import type { NextApiRequest, NextApiResponse } from 'next';
import { getVerticalFarmController } from '../../../lib/vertical-farming/controller';

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 { cropType, source } = req.query;

    const controller = getVerticalFarmController();
    let recipes = controller.getRecipes();

    // Filter by crop type if provided
    if (cropType && typeof cropType === 'string') {
      recipes = recipes.filter(r => r.cropType.toLowerCase() === cropType.toLowerCase());
    }

    // Filter by source if provided
    if (source && typeof source === 'string') {
      recipes = recipes.filter(r => r.source === source);
    }

    // Sort by rating (highest first) then by times used
    recipes.sort((a, b) => {
      if ((b.rating || 0) !== (a.rating || 0)) {
        return (b.rating || 0) - (a.rating || 0);
      }
      return b.timesUsed - a.timesUsed;
    });

    res.status(200).json({
      success: true,
      data: {
        totalRecipes: recipes.length,
        recipes: recipes.map(recipe => ({
          id: recipe.id,
          name: recipe.name,
          cropType: recipe.cropType,
          variety: recipe.variety,
          version: recipe.version,
          expectedDays: recipe.expectedDays,
          expectedYieldGrams: recipe.expectedYieldGrams,
          expectedYieldPerSqm: recipe.expectedYieldPerSqm,
          requirements: recipe.requirements,
          source: recipe.source,
          rating: recipe.rating,
          timesUsed: recipe.timesUsed,
          stages: recipe.stages.map(s => ({
            name: s.name,
            daysStart: s.daysStart,
            daysEnd: s.daysEnd
          }))
        }))
      }
    });
  } catch (error: any) {
    console.error('Error fetching recipes:', error);
    res.status(500).json({ success: false, error: error.message || 'Internal server error' });
  }
}
