/**
 * API Route: Get farm analytics
 * GET /api/vertical-farm/[farmId]/analytics
 */

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 !== 'GET') {
    return res.status(405).json({ success: false, error: 'Method not allowed' });
  }

  try {
    const { farmId, periodDays } = req.query;

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

    const days = periodDays ? parseInt(periodDays as string, 10) : 30;

    if (isNaN(days) || days < 1 || days > 365) {
      return res.status(400).json({
        success: false,
        error: 'periodDays must be a number between 1 and 365'
      });
    }

    const controller = getVerticalFarmController();
    const farm = controller.getFarm(farmId);

    if (!farm) {
      return res.status(404).json({
        success: false,
        error: `Farm not found: ${farmId}`
      });
    }

    const analytics = controller.generateAnalytics(farmId, days);

    res.status(200).json({
      success: true,
      data: analytics
    });
  } catch (error: any) {
    console.error('Error generating analytics:', error);
    res.status(500).json({ success: false, error: error.message || 'Internal server error' });
  }
}
