import { Request, Response } from 'express';
import { User } from '@models/User';
import { updateNotificationPreferencesSchema } from '@validators/userPreference.validator';
import logger from '@utils/logger';

/**
 * Get current user's notification preferences
 */
export const getNotificationPreferences = async (req: Request, res: Response): Promise<void> => {
  try {
    const userId = req.user!.userId;

    const user = await User.findByPk(userId, {
      attributes: [
        'userId',
        'emailNotificationsEnabled',
        'pushNotificationsEnabled',
        'inAppNotificationsEnabled'
      ]
    });

    if (!user) {
      res.status(404).json({
        success: false,
        message: 'User not found'
      });
      return;
    }

    logger.info(`[UserPreference] Retrieved notification preferences for user ${userId}`);

    res.json({
      success: true,
      data: {
        emailNotificationsEnabled: user.emailNotificationsEnabled,
        pushNotificationsEnabled: user.pushNotificationsEnabled,
        inAppNotificationsEnabled: user.inAppNotificationsEnabled
      }
    });
  } catch (error: any) {
    logger.error('[UserPreference] Failed to get notification preferences:', error);
    res.status(500).json({
      success: false,
      message: 'Failed to retrieve notification preferences',
      error: error.message
    });
  }
};

/**
 * Update current user's notification preferences
 */
export const updateNotificationPreferences = async (req: Request, res: Response): Promise<void> => {
  try {
    const userId = req.user!.userId;

    // Validate request body
    const validated = updateNotificationPreferencesSchema.parse(req.body);

    const user = await User.findByPk(userId);

    if (!user) {
      res.status(404).json({
        success: false,
        message: 'User not found'
      });
      return;
    }

    // Update only provided fields
    const updateData: any = {};
    if (validated.emailNotificationsEnabled !== undefined) {
      updateData.emailNotificationsEnabled = validated.emailNotificationsEnabled;
    }
    if (validated.pushNotificationsEnabled !== undefined) {
      updateData.pushNotificationsEnabled = validated.pushNotificationsEnabled;
    }
    if (validated.inAppNotificationsEnabled !== undefined) {
      updateData.inAppNotificationsEnabled = validated.inAppNotificationsEnabled;
    }

    await user.update(updateData);

    logger.info(`[UserPreference] Updated notification preferences for user ${userId}:`, updateData);

    res.json({
      success: true,
      message: 'Notification preferences updated successfully',
      data: {
        emailNotificationsEnabled: user.emailNotificationsEnabled,
        pushNotificationsEnabled: user.pushNotificationsEnabled,
        inAppNotificationsEnabled: user.inAppNotificationsEnabled
      }
    });
  } catch (error: any) {
    if (error.name === 'ZodError') {
      res.status(400).json({
        success: false,
        message: 'Validation failed',
        error: error.errors.map((e: any) => e.message).join(', ')
      });
      return;
    }

    logger.error('[UserPreference] Failed to update notification preferences:', error);
    res.status(500).json({
      success: false,
      message: 'Failed to update notification preferences',
      error: error.message
    });
  }
};

