/**
 * Plant Analytics API
 * Returns plant-specific analytics data
 */

import type { NextApiRequest, NextApiResponse } from 'next';
import { getPlantAnalytics, 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 species = req.query.species ? (req.query.species as string).split(',') : undefined;

    const filters: AnalyticsFilters = {
      timeRange,
      species,
    };

    const plantAnalytics = await getPlantAnalytics(filters);

    res.status(200).json({
      success: true,
      data: plantAnalytics,
      meta: {
        timeRange,
        filters: { species },
        generatedAt: new Date().toISOString(),
      },
    });
  } catch (error) {
    console.error('Plant analytics error:', error);
    res.status(500).json({
      success: false,
      error: 'Failed to fetch plant analytics',
    });
  }
}
