/**
 * API Route: Get connection suggestions for a plant
 * GET /api/plants/connections?plantId=xyz&maxDistance=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 { plantId, maxDistance } = 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 maxDistanceKm = maxDistance ? parseFloat(maxDistance as string) : 50;

    // Get all plants
    const allPlants = Array.from(
      new Set(blockchain.chain.map(block => block.plant.id))
    ).map(id => blockchain.getPlant(id)!).filter(Boolean);

    // Get connection suggestions
    const geoService = getGeolocationService();
    const suggestions = geoService.suggestConnections(
      plant,
      allPlants,
      maxDistanceKm
    );

    res.status(200).json({
      success: true,
      plant: {
        id: plant.id,
        commonName: plant.commonName,
        owner: plant.owner.name,
      },
      suggestionCount: suggestions.length,
      suggestions: suggestions.slice(0, 20), // Limit to top 20
    });
  } catch (error: any) {
    console.error('Error getting connection suggestions:', error);
    res.status(500).json({ error: error.message || 'Internal server error' });
  }
}
