/**
 * API Route: Register new vertical farm
 * POST /api/vertical-farm/register
 */

import type { NextApiRequest, NextApiResponse } from 'next';
import { getVerticalFarmController } from '../../../lib/vertical-farming/controller';
import { VerticalFarm } from '../../../lib/vertical-farming/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 {
      name,
      ownerId,
      location,
      specs,
      zones,
      environmentalControl,
      irrigationSystem,
      lightingSystem,
      nutrientSystem,
      automationLevel,
      automationSystems
    } = req.body;

    // Validate required fields
    if (!name || !ownerId || !location || !specs) {
      return res.status(400).json({
        success: false,
        error: 'Missing required fields: name, ownerId, location, specs'
      });
    }

    const controller = getVerticalFarmController();

    const farm: VerticalFarm = {
      id: `farm-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`,
      name,
      ownerId,
      location,
      specs: {
        ...specs,
        certifications: specs.certifications || [],
        currentActivePlants: specs.currentActivePlants || 0
      },
      zones: zones || [],
      environmentalControl: environmentalControl || {
        hvacUnits: [],
        co2Injection: { type: 'tank', capacityKg: 0, currentLevelKg: 0, injectionRateKgPerHour: 0, status: 'off' },
        humidification: { type: 'ultrasonic', capacityLPerHour: 0, status: 'off', currentOutput: 0 },
        airCirculation: { fans: [] },
        controlMode: 'manual'
      },
      irrigationSystem: irrigationSystem || {
        type: 'recirculating',
        freshWaterTankL: 1000,
        freshWaterLevelL: 500,
        nutrientTankL: 500,
        nutrientLevelL: 250,
        wasteTankL: 200,
        wasteLevelL: 0,
        waterTreatment: { ro: false, uv: false, ozone: false, filtration: 'basic' },
        pumps: [],
        irrigationSchedule: []
      },
      lightingSystem: lightingSystem || {
        type: 'LED',
        fixtures: [],
        lightSchedules: [],
        totalWattage: 0,
        currentWattage: 0,
        efficacyUmolJ: 2.5
      },
      nutrientSystem: nutrientSystem || {
        mixingMethod: 'manual',
        stockSolutions: [],
        dosingPumps: [],
        currentRecipe: {
          id: 'default',
          name: 'Default Recipe',
          cropType: 'general',
          growthStage: 'vegetative',
          targetEc: 1.5,
          targetPh: 6.0,
          ratios: { n: 150, p: 50, k: 200, ca: 200, mg: 50, s: 60, fe: 3, mn: 0.5, zn: 0.05, cu: 0.02, b: 0.5, mo: 0.01 },
          dosingRatiosMlPerL: []
        },
        monitoring: {
          ec: 0,
          ph: 0,
          lastCalibration: new Date().toISOString(),
          calibrationDue: new Date(Date.now() + 30 * 24 * 60 * 60 * 1000).toISOString()
        }
      },
      automationLevel: automationLevel || 'manual',
      automationSystems: automationSystems || [],
      status: 'operational',
      operationalSince: new Date().toISOString(),
      lastMaintenanceDate: new Date().toISOString(),
      currentCapacityUtilization: 0,
      averageYieldEfficiency: 0,
      energyEfficiencyScore: 50
    };

    controller.registerFarm(farm);

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