/**
 * API Route: Get plant lineage (ancestors and descendants)
 * GET /api/plants/lineage/[id]
 */

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

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

  try {
    const { id } = req.query;

    if (!id || typeof id !== 'string') {
      return res.status(400).json({ error: 'Invalid plant ID' });
    }

    const blockchain = getBlockchain();
    const lineage = blockchain.getPlantLineage(id);

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

    res.status(200).json({
      success: true,
      lineage,
      stats: {
        ancestorCount: lineage.ancestors.length,
        descendantCount: lineage.descendants.length,
        siblingCount: lineage.siblings.length,
        generation: lineage.generation,
      },
    });
  } catch (error: any) {
    console.error('Error fetching plant lineage:', error);
    res.status(500).json({ error: error.message || 'Internal server error' });
  }
}
