/**
 * API Route: TransportTrackerAgent Savings Calculator
 * GET /api/agents/transport-tracker/savings - Calculate carbon savings vs conventional logistics
 */

import type { NextApiRequest, NextApiResponse } from 'next';
import { getTransportTrackerAgent } from '../../../../lib/agents/TransportTrackerAgent';

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 agent = getTransportTrackerAgent();
    const savings = agent.calculateSavingsVsConventional();
    const networkStats = agent.getNetworkStats();

    if (!networkStats || networkStats.totalEvents === 0) {
      return res.status(200).json({
        success: true,
        data: {
          message: 'No transport data available for savings calculation.',
          savings: null
        }
      });
    }

    // Calculate additional context metrics
    const context = {
      // Equivalent miles driven by average car (0.404 kg CO2 per mile)
      equivalentCarMiles: Math.round(savings.savedKg / 0.404),

      // Equivalent trees needed to absorb this CO2 (21 kg per tree per year)
      equivalentTreeYears: Math.round((savings.savedKg / 21) * 10) / 10,

      // Equivalent gallons of gasoline (8.887 kg CO2 per gallon)
      equivalentGallonsSaved: Math.round((savings.savedKg / 8.887) * 10) / 10,

      // Equivalent smartphone charges (0.0085 kg CO2 per charge)
      equivalentPhoneCharges: Math.round(savings.savedKg / 0.0085)
    };

    // Generate insights based on performance
    const insights: string[] = [];

    if (savings.savedPercentage >= 90) {
      insights.push('Exceptional performance! Your local supply chain is operating at near-optimal carbon efficiency.');
    } else if (savings.savedPercentage >= 70) {
      insights.push('Great job! Your local sourcing strategy is significantly reducing carbon emissions.');
    } else if (savings.savedPercentage >= 50) {
      insights.push('Good progress. There are still opportunities to further reduce your carbon footprint.');
    } else if (savings.savedPercentage > 0) {
      insights.push('Your local network is making a positive impact. Consider expanding local sourcing to improve further.');
    }

    if (networkStats.greenTransportPercentage >= 50) {
      insights.push(`${networkStats.greenTransportPercentage}% of your transport uses green methods - excellent sustainability focus!`);
    }

    res.status(200).json({
      success: true,
      data: {
        savings: {
          localGreenCarbonKg: savings.localGreenCarbon,
          conventionalCarbonKg: savings.conventionalCarbon,
          savedKg: savings.savedKg,
          savedPercentage: savings.savedPercentage
        },
        context,
        insights,
        methodology: {
          description: 'Savings calculated by comparing LocalGreenChain transport to conventional supply chain assumptions.',
          assumptions: [
            'Conventional: Average 1,500 miles transport per item at 0.2 kg CO2/mile',
            'LocalGreenChain: Actual tracked distances and transport methods',
            'Green methods include: walking, bicycle, electric vehicles, rail'
          ]
        }
      }
    });
  } catch (error: any) {
    console.error('Error calculating transport savings:', error);
    res.status(500).json({ success: false, error: error.message || 'Internal server error' });
  }
}
