/**
 * API Route: Find nearby plants
 * GET /api/plants/nearby?lat=123&lon=456&radius=50
 */

import type { NextApiRequest, NextApiResponse } from 'next';
import { getBlockchain } from '../../../lib/blockchain/manager';
import { getGeolocationService } from '../../../lib/services/geolocation';

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

  try {
    const { lat, lon, radius, species } = req.query;

    if (!lat || !lon) {
      return res.status(400).json({
        error: 'Missing required parameters: lat, lon',
      });
    }

    const latitude = parseFloat(lat as string);
    const longitude = parseFloat(lon as string);
    const radiusKm = radius ? parseFloat(radius as string) : 50;

    if (isNaN(latitude) || isNaN(longitude) || isNaN(radiusKm)) {
      return res.status(400).json({
        error: 'Invalid parameters: lat, lon, and radius must be numbers',
      });
    }

    const blockchain = getBlockchain();
    let nearbyPlants = blockchain.findNearbyPlants(latitude, longitude, radiusKm);

    // Filter by species if provided
    if (species && typeof species === 'string') {
      nearbyPlants = nearbyPlants.filter(
        np => np.plant.scientificName === species || np.plant.commonName === species
      );
    }

    // Get plant clusters
    const geoService = getGeolocationService();
    const allNearbyPlantData = nearbyPlants.map(np => np.plant);
    const clusters = geoService.findPlantClusters(allNearbyPlantData, 10);

    res.status(200).json({
      success: true,
      count: nearbyPlants.length,
      plants: nearbyPlants,
      clusters,
      searchParams: {
        latitude,
        longitude,
        radiusKm,
        species: species || null,
      },
    });
  } catch (error: any) {
    console.error('Error finding nearby plants:', error);
    res.status(500).json({ error: error.message || 'Internal server error' });
  }
}
