/**
 * API Route: Register a new plant
 * POST /api/plants/register
 */

import type { NextApiRequest, NextApiResponse } from 'next';
import { getBlockchain, saveBlockchain } from '../../../lib/blockchain/manager';
import { PlantData } from '../../../lib/blockchain/types';
import { getPlantsNetService } from '../../../lib/services/plantsnet';

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

  try {
    const plantData: PlantData = req.body;

    // Validate required fields
    if (!plantData.id || !plantData.commonName || !plantData.owner || !plantData.location) {
      return res.status(400).json({
        error: 'Missing required fields: id, commonName, owner, location',
      });
    }

    const blockchain = getBlockchain();

    // Register the plant
    const block = blockchain.registerPlant(plantData);

    // Optionally report to plants.net
    if (process.env.PLANTS_NET_API_KEY) {
      const plantsNet = getPlantsNetService();
      const result = await plantsNet.reportPlantToNetwork({
        commonName: plantData.commonName,
        scientificName: plantData.scientificName,
        location: plantData.location,
        ownerId: plantData.owner.id,
        propagationType: plantData.propagationType,
      });

      if (result.success && result.plantsNetId) {
        // Update plant with plants.net ID
        blockchain.updatePlantStatus(plantData.id, {
          plantsNetId: result.plantsNetId,
        });
      }
    }

    // Save blockchain
    saveBlockchain();

    res.status(201).json({
      success: true,
      plant: block.plant,
      block: {
        index: block.index,
        hash: block.hash,
        timestamp: block.timestamp,
      },
    });
  } catch (error: any) {
    console.error('Error registering plant:', error);
    res.status(500).json({ error: error.message || 'Internal server error' });
  }
}
