import { Response, NextFunction } from 'express';
import { AuthRequest } from '../../shared/middleware/auth';
import { ResponseFormatter } from '../../shared/utils/responseFormatter';
import { notificationsService } from './notifications.service';

class NotificationsController {
  async listMyNotifications(req: AuthRequest, res: Response, next: NextFunction) {
    try {
      const page = Number(req.query.page || 1);
      const pageSize = Number(req.query.pageSize || 20);

      const result = await notificationsService.listMyNotifications(
        req.user!.id,
        page,
        pageSize
      );

      res.json(
        ResponseFormatter.success(result)
      );
    } catch (error) {
      next(error);
    }
  }

  async getUnreadCount(req: AuthRequest, res: Response, next: NextFunction) {
    try {
      const result = await notificationsService.getUnreadCount(req.user!.id);
      res.json(ResponseFormatter.success(result));
    } catch (error) {
      next(error);
    }
  }

  async markAsRead(req: AuthRequest, res: Response, next: NextFunction) {
    try {
      const notification = await notificationsService.markAsRead(
        req.params.id,
        req.user!.id
      );

      res.json(
        ResponseFormatter.success(notification, 'تم تعليم الإشعار كمقروء - Notification marked as read')
      );
    } catch (error) {
      next(error);
    }
  }

  async markAllAsRead(req: AuthRequest, res: Response, next: NextFunction) {
    try {
      const result = await notificationsService.markAllAsRead(req.user!.id);

      res.json(
        ResponseFormatter.success(result, 'تم تعليم كل الإشعارات كمقروءة - All notifications marked as read')
      );
    } catch (error) {
      next(error);
    }
  }
}

export const notificationsController = new NotificationsController();