/**
 * API Route: Consumer preferences
 * POST - Register/update consumer preferences
 * GET - Get consumer preferences
 */

import type { NextApiRequest, NextApiResponse } from 'next';
import { getDemandForecaster } from '../../../lib/demand/forecaster';
import { ConsumerPreference } from '../../../lib/demand/types';

export default async function handler(
  req: NextApiRequest,
  res: NextApiResponse
) {
  const forecaster = getDemandForecaster();

  if (req.method === 'POST') {
    try {
      const preference = req.body as ConsumerPreference;

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

      // Add timestamps
      const now = new Date().toISOString();
      preference.createdAt = preference.createdAt || now;
      preference.updatedAt = now;

      // Set defaults
      preference.householdSize = preference.householdSize || 1;
      preference.dietaryType = preference.dietaryType || ['omnivore'];
      preference.allergies = preference.allergies || [];
      preference.dislikes = preference.dislikes || [];
      preference.preferredCategories = preference.preferredCategories || [];
      preference.certificationPreferences = preference.certificationPreferences || [];
      preference.freshnessImportance = preference.freshnessImportance || 3;
      preference.priceImportance = preference.priceImportance || 3;
      preference.sustainabilityImportance = preference.sustainabilityImportance || 3;
      preference.deliveryPreferences = preference.deliveryPreferences || {
        method: ['home_delivery'],
        frequency: 'weekly',
        preferredDays: ['saturday']
      };

      forecaster.registerPreference(preference);

      res.status(201).json({
        success: true,
        data: preference
      });
    } catch (error: any) {
      console.error('Error registering preference:', error);
      res.status(500).json({ success: false, error: error.message || 'Internal server error' });
    }
  } else if (req.method === 'GET') {
    try {
      const { consumerId } = req.query;

      if (!consumerId || typeof consumerId !== 'string') {
        return res.status(400).json({
          success: false,
          error: 'Consumer ID is required'
        });
      }

      // Access internal state for lookup
      const state = forecaster.toJSON() as any;
      const preferences = state.preferences as [string, ConsumerPreference][];
      const preference = preferences.find(([id]) => id === consumerId);

      if (!preference) {
        return res.status(404).json({
          success: false,
          error: `Preference not found for consumer: ${consumerId}`
        });
      }

      res.status(200).json({
        success: true,
        data: preference[1]
      });
    } catch (error: any) {
      console.error('Error fetching preference:', error);
      res.status(500).json({ success: false, error: error.message || 'Internal server error' });
    }
  } else {
    return res.status(405).json({ success: false, error: 'Method not allowed' });
  }
}
