/**
 * API Route: Record seed saving event
 * POST /api/transport/seed-saving
 */

import type { NextApiRequest, NextApiResponse } from 'next';
import { getTransportChain } from '../../../lib/transport/tracker';
import { SeedSavingEvent, TransportLocation, TransportMethod } from '../../../lib/transport/types';

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

  try {
    const {
      parentPlantIds,
      newSeedBatchId,
      collectionMethod,
      seedCount,
      seedWeight,
      seedWeightUnit,
      storageConditions,
      storageLocationId,
      newGenerationNumber,
      fromLocation,
      toLocation,
      transportMethod,
      senderId,
      receiverId,
      distanceKm,
      durationMinutes,
      viabilityTestDate,
      germinationRate,
      availableForSharing,
      sharingTerms,
      notes
    } = req.body;

    // Validate required fields
    if (!parentPlantIds || !newSeedBatchId || !collectionMethod || !storageConditions || !storageLocationId || !fromLocation || !toLocation || !senderId || !receiverId) {
      return res.status(400).json({
        success: false,
        error: 'Missing required fields: parentPlantIds, newSeedBatchId, collectionMethod, storageConditions, storageLocationId, fromLocation, toLocation, senderId, receiverId'
      });
    }

    const transportChain = getTransportChain();

    const event: SeedSavingEvent = {
      id: `seed-save-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`,
      timestamp: new Date().toISOString(),
      eventType: 'seed_saving',
      parentPlantIds: Array.isArray(parentPlantIds) ? parentPlantIds : [parentPlantIds],
      newSeedBatchId,
      collectionMethod,
      seedCount,
      seedWeight,
      seedWeightUnit,
      storageConditions,
      storageLocationId,
      newGenerationNumber: newGenerationNumber || 1,
      viabilityTestDate,
      germinationRate,
      availableForSharing: availableForSharing || false,
      sharingTerms,
      fromLocation: fromLocation as TransportLocation,
      toLocation: toLocation as TransportLocation,
      distanceKm: distanceKm || 0,
      durationMinutes: durationMinutes || 0,
      transportMethod: (transportMethod as TransportMethod) || 'walking',
      carbonFootprintKg: 0,
      senderId,
      receiverId,
      status: 'verified',
      notes
    };

    const block = transportChain.recordEvent(event);

    res.status(201).json({
      success: true,
      data: {
        event,
        block: {
          index: block.index,
          hash: block.hash,
          timestamp: block.timestamp,
          cumulativeCarbonKg: block.cumulativeCarbonKg,
          cumulativeFoodMiles: block.cumulativeFoodMiles
        }
      }
    });
  } catch (error: any) {
    console.error('Error recording seed saving event:', error);
    res.status(500).json({ success: false, error: error.message || 'Internal server error' });
  }
}
