/**
 * API Route: Clone a plant (create offspring)
 * POST /api/plants/clone
 */

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

interface CloneRequest {
  parentPlantId: string;
  propagationType: 'seed' | 'clone' | 'cutting' | 'division' | 'grafting';
  newPlant: Partial<PlantData>;
}

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

  try {
    const { parentPlantId, propagationType, newPlant }: CloneRequest = req.body;

    // Validate required fields
    if (!parentPlantId || !propagationType || !newPlant) {
      return res.status(400).json({
        error: 'Missing required fields: parentPlantId, propagationType, newPlant',
      });
    }

    if (!newPlant.location || !newPlant.owner) {
      return res.status(400).json({
        error: 'New plant must have location and owner',
      });
    }

    const blockchain = getBlockchain();

    // Clone the plant
    const block = blockchain.clonePlant(
      parentPlantId,
      newPlant,
      propagationType
    );

    // Save blockchain
    saveBlockchain();

    // Get parent for context
    const parent = blockchain.getPlant(parentPlantId);

    res.status(201).json({
      success: true,
      plant: block.plant,
      parent: parent,
      block: {
        index: block.index,
        hash: block.hash,
        timestamp: block.timestamp,
      },
      message: `Successfully created ${propagationType} from parent plant`,
    });
  } catch (error: any) {
    console.error('Error cloning plant:', error);
    res.status(500).json({ error: error.message || 'Internal server error' });
  }
}
