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

import type { NextApiRequest, NextApiResponse } from 'next';
import { getTransportChain } from '../../../lib/transport/tracker';
import { SeedAcquisitionEvent, 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 {
      seedBatchId,
      sourceType,
      species,
      variety,
      quantity,
      quantityUnit,
      generation,
      fromLocation,
      toLocation,
      transportMethod,
      senderId,
      receiverId,
      distanceKm,
      durationMinutes,
      germinationRate,
      certifications,
      notes
    } = req.body;

    // Validate required fields
    if (!seedBatchId || !sourceType || !species || !quantity || !fromLocation || !toLocation || !senderId || !receiverId) {
      return res.status(400).json({
        success: false,
        error: 'Missing required fields: seedBatchId, sourceType, species, quantity, fromLocation, toLocation, senderId, receiverId'
      });
    }

    const transportChain = getTransportChain();

    // Calculate distance if not provided
    const calculatedDistance = distanceKm ??
      (fromLocation && toLocation ?
        Math.sqrt(
          Math.pow((toLocation.latitude - fromLocation.latitude) * 111, 2) +
          Math.pow((toLocation.longitude - fromLocation.longitude) * 111 * Math.cos(fromLocation.latitude * Math.PI / 180), 2)
        ) : 0);

    const event: SeedAcquisitionEvent = {
      id: `seed-acq-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`,
      timestamp: new Date().toISOString(),
      eventType: 'seed_acquisition',
      seedBatchId,
      sourceType,
      species,
      variety,
      quantity,
      quantityUnit: quantityUnit || 'seeds',
      generation: generation || 0,
      fromLocation: fromLocation as TransportLocation,
      toLocation: toLocation as TransportLocation,
      distanceKm: calculatedDistance,
      durationMinutes: durationMinutes || 0,
      transportMethod: (transportMethod as TransportMethod) || 'local_delivery',
      carbonFootprintKg: 0, // Will be calculated by tracker
      senderId,
      receiverId,
      status: 'verified',
      germinationRate,
      certifications,
      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 acquisition:', error);
    res.status(500).json({ success: false, error: error.message || 'Internal server error' });
  }
}
