/**
 * API Route: Create market match
 * POST /api/demand/match
 */

import type { NextApiRequest, NextApiResponse } from 'next';
import { getDemandForecaster } from '../../../lib/demand/forecaster';
import { MarketMatch } 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 {
      demandSignalId,
      supplyCommitmentId,
      consumerId,
      growerId,
      produceType,
      matchedQuantityKg,
      agreedPricePerKg,
      currency,
      deliveryDate,
      deliveryMethod,
      deliveryLocation
    } = req.body;

    // Validate required fields
    if (!demandSignalId || !supplyCommitmentId || !consumerId || !growerId || !produceType || !matchedQuantityKg || !agreedPricePerKg || !deliveryDate || !deliveryMethod || !deliveryLocation) {
      return res.status(400).json({
        success: false,
        error: 'Missing required fields: demandSignalId, supplyCommitmentId, consumerId, growerId, produceType, matchedQuantityKg, agreedPricePerKg, deliveryDate, deliveryMethod, deliveryLocation'
      });
    }

    const match: MarketMatch = {
      id: `match-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`,
      timestamp: new Date().toISOString(),
      demandSignalId,
      supplyCommitmentId,
      consumerId,
      growerId,
      produceType,
      matchedQuantityKg,
      agreedPricePerKg,
      totalPrice: matchedQuantityKg * agreedPricePerKg,
      currency: currency || 'USD',
      deliveryDate,
      deliveryMethod,
      deliveryLocation,
      status: 'pending'
    };

    // Store the match (in a real implementation, this would update the forecaster's internal state)
    // For now, we'll just return the match
    // The forecaster would track this to update supply commitment remaining quantities

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