const { validationResult } = require('express-validator');
const NotificationService = require('../services/notificationService');
const logger = require('../config/logger');

/**
 * Notification Controller
 * Handles notification API endpoints
 */
class NotificationController {
  /**
   * Get user's notifications with filtering and pagination
   * @route GET /api/v1/notifications
   */
  static async getNotifications(req, res, next) {
    try {
      const errors = validationResult(req);
      if (!errors.isEmpty()) {
        return res.status(400).json({
          code: 400,
          message: 'Invalid request parameters',
          data: null,
          errors: errors.array(),
        });
      }

      const { page = 1, limit = 10, type } = req.query;
      const userId = req.userId;
      const language = req.language || 'zh';

      const result = await NotificationService.getUserNotifications(userId, {
        page: parseInt(page),
        limit: parseInt(limit),
        type,
      });

      // 返回本地化内容
      const localizedData = result.data.map(notification => 
        NotificationService.getLocalizedNotification(notification, language)
      );

      res.json({
        code: 0,
        message: 'Success',
        data: localizedData,
        pagination: result.pagination,
      });
    } catch (error) {
      logger.error('Error in getNotifications:', error);
      next(error);
    }
  }

  /**
   * Mark notification as read
   * @route PUT /api/v1/notifications/:id/read
   */
  static async markAsRead(req, res, next) {
    try {
      const errors = validationResult(req);
      if (!errors.isEmpty()) {
        return res.status(400).json({
          success: false,
          error: {
            code: 'VALIDATION_ERROR',
            message: 'Invalid request parameters',
            details: errors.array(),
          },
        });
      }

      const { id } = req.params;
      const userId = req.userId;

      const notification = await NotificationService.markAsRead(id, userId);

      res.json({
        success: true,
        data: notification,
      });
    } catch (error) {
      logger.error('Error in markAsRead:', error);

      if (error.message === 'NOTIFICATION_NOT_FOUND') {
        return res.status(404).json({
          success: false,
          error: {
            code: 'NOTIFICATION_NOT_FOUND',
            message: 'Notification not found',
          },
        });
      }

      next(error);
    }
  }

  /**
   * Get unread notification counts by type
   * @route GET /api/v1/notifications/unread-count
   */
  static async getUnreadCounts(req, res, next) {
    try {
      const userId = req.userId;
      const counts = await NotificationService.getUnreadCounts(userId);

      res.json({
        code: 0,
        message: 'Success',
        data: counts,
      });
    } catch (error) {
      logger.error('Error in getUnreadCounts:', error);
      next(error);
    }
  }

  /**
   * Mark all notifications as read
   * @route PUT /api/v1/notifications/read-all
   */
  static async markAllAsRead(req, res, next) {
    try {
      const userId = req.userId;

      const updatedCount = await NotificationService.markAllAsRead(userId);

      res.json({
        success: true,
        data: {
          updatedCount,
        },
      });
    } catch (error) {
      logger.error('Error in markAllAsRead:', error);
      next(error);
    }
  }

  /**
   * Delete notification
   * @route DELETE /api/v1/notifications/:id
   */
  static async deleteNotification(req, res, next) {
    try {
      const errors = validationResult(req);
      if (!errors.isEmpty()) {
        return res.status(400).json({
          success: false,
          error: {
            code: 'VALIDATION_ERROR',
            message: 'Invalid request parameters',
            details: errors.array(),
          },
        });
      }

      const { id } = req.params;
      const userId = req.userId;

      await NotificationService.deleteNotification(id, userId);

      res.json({
        success: true,
        data: {
          message: 'Notification deleted successfully',
        },
      });
    } catch (error) {
      logger.error('Error in deleteNotification:', error);

      if (error.message === 'NOTIFICATION_NOT_FOUND') {
        return res.status(404).json({
          success: false,
          error: {
            code: 'NOTIFICATION_NOT_FOUND',
            message: 'Notification not found',
          },
        });
      }

      next(error);
    }
  }
}

module.exports = NotificationController;
