/**
 * API Route: Register supply commitment
 * POST /api/demand/supply
 */

import type { NextApiRequest, NextApiResponse } from 'next';
import { getDemandForecaster } from '../../../lib/demand/forecaster';
import { SupplyCommitment } from '../../../lib/demand/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 {
      growerId,
      produceType,
      variety,
      committedQuantityKg,
      availableFrom,
      availableUntil,
      pricePerKg,
      currency,
      minimumOrderKg,
      certifications,
      freshnessGuaranteeHours,
      deliveryRadiusKm,
      deliveryMethods,
      bulkDiscountThreshold,
      bulkDiscountPercent
    } = req.body;

    // Validate required fields
    if (!growerId || !produceType || !committedQuantityKg || !availableFrom || !availableUntil || !pricePerKg) {
      return res.status(400).json({
        success: false,
        error: 'Missing required fields: growerId, produceType, committedQuantityKg, availableFrom, availableUntil, pricePerKg'
      });
    }

    const commitment: SupplyCommitment = {
      id: `supply-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`,
      growerId,
      timestamp: new Date().toISOString(),
      produceType,
      variety,
      committedQuantityKg,
      availableFrom,
      availableUntil,
      pricePerKg,
      currency: currency || 'USD',
      minimumOrderKg: minimumOrderKg || 0.5,
      bulkDiscountThreshold,
      bulkDiscountPercent,
      certifications: certifications || [],
      freshnessGuaranteeHours: freshnessGuaranteeHours || 24,
      deliveryRadiusKm: deliveryRadiusKm || 50,
      deliveryMethods: deliveryMethods || ['customer_pickup', 'grower_delivery'],
      status: 'available',
      remainingKg: committedQuantityKg
    };

    const forecaster = getDemandForecaster();
    forecaster.registerSupply(commitment);

    res.status(201).json({
      success: true,
      data: commitment
    });
  } catch (error: any) {
    console.error('Error registering supply commitment:', error);
    res.status(500).json({ success: false, error: error.message || 'Internal server error' });
  }
}
