/**
 * API Route: Start crop batch
 * POST /api/vertical-farm/batch/start
 */

import type { NextApiRequest, NextApiResponse } from 'next';
import { getVerticalFarmController } from '../../../../lib/vertical-farming/controller';

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 {
      farmId,
      zoneId,
      recipeId,
      seedBatchId,
      plantCount
    } = req.body;

    // Validate required fields
    if (!farmId || !zoneId || !recipeId || !seedBatchId || !plantCount) {
      return res.status(400).json({
        success: false,
        error: 'Missing required fields: farmId, zoneId, recipeId, seedBatchId, plantCount'
      });
    }

    if (plantCount < 1) {
      return res.status(400).json({
        success: false,
        error: 'plantCount must be at least 1'
      });
    }

    const controller = getVerticalFarmController();

    // Verify farm exists
    const farm = controller.getFarm(farmId);
    if (!farm) {
      return res.status(404).json({
        success: false,
        error: `Farm not found: ${farmId}`
      });
    }

    // Verify zone exists
    const zone = farm.zones.find(z => z.id === zoneId);
    if (!zone) {
      return res.status(404).json({
        success: false,
        error: `Zone not found: ${zoneId}`
      });
    }

    // Verify recipe exists
    const recipes = controller.getRecipes();
    const recipe = recipes.find(r => r.id === recipeId);
    if (!recipe) {
      return res.status(404).json({
        success: false,
        error: `Recipe not found: ${recipeId}`
      });
    }

    const batch = controller.startCropBatch(farmId, zoneId, recipeId, seedBatchId, plantCount);

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