/**
 * Sustainability Analytics API
 * Returns environmental impact and sustainability metrics
 */

import type { NextApiRequest, NextApiResponse } from 'next';
import { getSustainabilityAnalytics, AnalyticsFilters, TimeRange } from '../../../lib/analytics';

export default async function handler(
  req: NextApiRequest,
  res: NextApiResponse
) {
  if (req.method !== 'GET') {
    return res.status(405).json({ error: 'Method not allowed' });
  }

  try {
    const timeRange = (req.query.timeRange as TimeRange) || '30d';

    const filters: AnalyticsFilters = {
      timeRange,
    };

    const sustainabilityAnalytics = await getSustainabilityAnalytics(filters);

    res.status(200).json({
      success: true,
      data: sustainabilityAnalytics,
      meta: {
        timeRange,
        generatedAt: new Date().toISOString(),
      },
    });
  } catch (error) {
    console.error('Sustainability analytics error:', error);
    res.status(500).json({
      success: false,
      error: 'Failed to fetch sustainability analytics',
    });
  }
}
