/**
 * API Route: Complete harvest
 * POST /api/vertical-farm/batch/[batchId]/harvest
 */

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 { batchId } = req.query;
    const { actualYieldKg, qualityGrade } = req.body;

    if (!batchId || typeof batchId !== 'string') {
      return res.status(400).json({
        success: false,
        error: 'Batch ID is required'
      });
    }

    // Validate required fields
    if (actualYieldKg === undefined || !qualityGrade) {
      return res.status(400).json({
        success: false,
        error: 'Missing required fields: actualYieldKg, qualityGrade'
      });
    }

    // Validate quality grade
    const validGrades = ['A', 'B', 'C', 'processing'];
    if (!validGrades.includes(qualityGrade)) {
      return res.status(400).json({
        success: false,
        error: 'Invalid qualityGrade. Must be one of: A, B, C, processing'
      });
    }

    if (actualYieldKg < 0) {
      return res.status(400).json({
        success: false,
        error: 'actualYieldKg must be a positive number'
      });
    }

    const controller = getVerticalFarmController();

    // Verify batch exists
    const state = controller.toJSON() as any;
    const batches = state.batches as [string, any][];
    const batchEntry = batches.find(([id]) => id === batchId);

    if (!batchEntry) {
      return res.status(404).json({
        success: false,
        error: `Batch not found: ${batchId}`
      });
    }

    const completedBatch = controller.completeHarvest(batchId, actualYieldKg, qualityGrade);

    res.status(200).json({
      success: true,
      data: {
        batch: completedBatch,
        yieldEfficiency: completedBatch.expectedYieldKg > 0
          ? Math.round((actualYieldKg / completedBatch.expectedYieldKg) * 100)
          : 0
      }
    });
  } catch (error: any) {
    console.error('Error completing harvest:', error);
    res.status(500).json({ success: false, error: error.message || 'Internal server error' });
  }
}
