/**
 * API: Notification Preferences Endpoint
 * GET /api/notifications/preferences - Get user preferences
 * PUT /api/notifications/preferences - Update user preferences
 */

import type { NextApiRequest, NextApiResponse } from 'next';
import { getNotificationService } from '../../../lib/notifications';

export default async function handler(
  req: NextApiRequest,
  res: NextApiResponse
) {
  const notificationService = getNotificationService();
  // In production, get userId from session/auth
  const userId = req.query.userId as string || req.body?.userId || 'demo-user';

  if (req.method === 'GET') {
    try {
      const preferences = notificationService.getUserPreferences(userId);

      return res.status(200).json({
        success: true,
        data: preferences
      });
    } catch (error: any) {
      return res.status(500).json({
        success: false,
        error: error.message
      });
    }
  }

  if (req.method === 'PUT') {
    try {
      const {
        email,
        push,
        inApp,
        plantReminders,
        transportAlerts,
        farmAlerts,
        harvestAlerts,
        demandMatches,
        weeklyDigest,
        quietHoursStart,
        quietHoursEnd,
        timezone
      } = req.body;

      const preferences = notificationService.updatePreferences(userId, {
        email,
        push,
        inApp,
        plantReminders,
        transportAlerts,
        farmAlerts,
        harvestAlerts,
        demandMatches,
        weeklyDigest,
        quietHoursStart,
        quietHoursEnd,
        timezone
      });

      return res.status(200).json({
        success: true,
        data: preferences
      });
    } catch (error: any) {
      return res.status(500).json({
        success: false,
        error: error.message
      });
    }
  }

  return res.status(405).json({ error: 'Method not allowed' });
}
