/**
 * API Route: Get plant details by ID
 * GET /api/plants/[id]
 * PUT /api/plants/[id] - Update plant status
 */

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

export default async function handler(
  req: NextApiRequest,
  res: NextApiResponse
) {
  const { id } = req.query;

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

  const blockchain = getBlockchain();

  if (req.method === 'GET') {
    try {
      const plant = blockchain.getPlant(id);

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

      res.status(200).json({
        success: true,
        plant,
      });
    } catch (error: any) {
      console.error('Error fetching plant:', error);
      res.status(500).json({ error: error.message || 'Internal server error' });
    }
  } else if (req.method === 'PUT') {
    try {
      const updates = req.body;

      const block = blockchain.updatePlantStatus(id, updates);

      // Save blockchain
      saveBlockchain();

      res.status(200).json({
        success: true,
        plant: block.plant,
        message: 'Plant updated successfully',
      });
    } catch (error: any) {
      console.error('Error updating plant:', error);
      res.status(500).json({ error: error.message || 'Internal server error' });
    }
  } else {
    res.status(405).json({ error: 'Method not allowed' });
  }
}
