/**
 * API Route: Compare growing environments of two plants
 * GET /api/environment/compare?plant1=xyz&plant2=abc
 */

import type { NextApiRequest, NextApiResponse } from 'next';
import { getBlockchain } from '../../../lib/blockchain/manager';
import { compareEnvironments } 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 { plant1, plant2 } = req.query;

    if (!plant1 || !plant2 || typeof plant1 !== 'string' || typeof plant2 !== 'string') {
      return res.status(400).json({ error: 'Missing plant1 and plant2 parameters' });
    }

    const blockchain = getBlockchain();
    const plantData1 = blockchain.getPlant(plant1);
    const plantData2 = blockchain.getPlant(plant2);

    if (!plantData1 || !plantData2) {
      return res.status(404).json({ error: 'One or both plants not found' });
    }

    if (!plantData1.environment || !plantData2.environment) {
      return res.status(400).json({
        error: 'Both plants must have environmental data',
        plant1HasData: !!plantData1.environment,
        plant2HasData: !!plantData2.environment,
      });
    }

    const comparison = compareEnvironments(plantData1.environment, plantData2.environment);
    comparison.plant1 = plant1;
    comparison.plant2 = plant2;

    res.status(200).json({
      success: true,
      plants: {
        plant1: {
          id: plantData1.id,
          commonName: plantData1.commonName,
          scientificName: plantData1.scientificName,
          owner: plantData1.owner.name,
        },
        plant2: {
          id: plantData2.id,
          commonName: plantData2.commonName,
          scientificName: plantData2.scientificName,
          owner: plantData2.owner.name,
        },
      },
      comparison: {
        similarityScore: comparison.score,
        similarities: comparison.similarities,
        differences: comparison.differences,
      },
      interpretation: getScoreInterpretation(comparison.score),
    });
  } catch (error: any) {
    console.error('Error comparing environments:', error);
    res.status(500).json({ error: error.message || 'Internal server error' });
  }
}

function getScoreInterpretation(score: number): string {
  if (score >= 90) return 'Nearly identical growing conditions';
  if (score >= 75) return 'Very similar environments - likely to have similar results';
  if (score >= 60) return 'Moderately similar conditions';
  if (score >= 40) return 'Some similarities but notable differences';
  return 'Very different growing environments';
}
