/**
 * API Route: Get environmental recommendations for a plant
 * GET /api/environment/recommendations?plantId=xyz
 */

import type { NextApiRequest, NextApiResponse } from 'next';
import { getBlockchain } from '../../../lib/blockchain/manager';
import {
  generateRecommendations,
  calculateEnvironmentalHealth,
} from '../../../lib/environment/analysis';

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

  try {
    const { plantId } = req.query;

    if (!plantId || typeof plantId !== 'string') {
      return res.status(400).json({ error: 'Missing plantId parameter' });
    }

    const blockchain = getBlockchain();
    const plant = blockchain.getPlant(plantId);

    if (!plant) {
      return res.status(404).json({ error: 'Plant not found' });
    }

    const recommendations = generateRecommendations(plant);

    const healthScore = plant.environment
      ? calculateEnvironmentalHealth(plant.environment)
      : null;

    res.status(200).json({
      success: true,
      plant: {
        id: plant.id,
        commonName: plant.commonName,
        scientificName: plant.scientificName,
      },
      environmentalHealth: healthScore,
      recommendations,
      summary: {
        criticalIssues: recommendations.filter(r => r.priority === 'critical').length,
        highPriority: recommendations.filter(r => r.priority === 'high').length,
        mediumPriority: recommendations.filter(r => r.priority === 'medium').length,
        lowPriority: recommendations.filter(r => r.priority === 'low').length,
      },
    });
  } catch (error: any) {
    console.error('Error generating recommendations:', error);
    res.status(500).json({ error: error.message || 'Internal server error' });
  }
}
