import { Controller, Get, Patch, Query, Param, Logger, BadRequestException, ParseIntPipe } from '@nestjs/common';
import { ApiTags, ApiOperation, ApiQuery, ApiParam } from '@nestjs/swagger';
import { Public } from '../../modules/auth/public.decorator';
import { MobileNotificationsService } from './mobile-notifications.service';

@ApiTags('mobile_notifications')
@Controller('mobile/notifications')
export class MobileNotificationsController {
  private readonly logger = new Logger(MobileNotificationsController.name);

  constructor(
    private readonly notificationsService: MobileNotificationsService,
  ) {}

  @Public()
  @Get()
  @ApiOperation({ summary: 'Get paginated notifications list for a mobile user' })
  @ApiQuery({ name: 'userId', required: true, type: Number, description: 'ID of the recipient user' })
  @ApiQuery({ name: 'page', required: false, type: Number, description: 'Page number (default: 1)' })
  @ApiQuery({ name: 'limit', required: false, type: Number, description: 'Items per page (default: 10)' })
  @ApiQuery({ name: 'status', required: false, type: String, description: 'Filter by notification status (pending, sent, failed)' })
  async getNotifications(
    @Query('userId') userIdRaw?: string,
    @Query('page') pageRaw?: string,
    @Query('limit') limitRaw?: string,
    @Query('status') status?: string,
  ) {
    if (!userIdRaw) {
      throw new BadRequestException('userId is required');
    }

    const userId = Number(userIdRaw);
    if (Number.isNaN(userId) || userId <= 0) {
      throw new BadRequestException('Invalid userId');
    }

    const page = pageRaw ? Number(pageRaw) : 1;
    const limit = limitRaw ? Number(limitRaw) : 10;

    const validatedPage = Number.isFinite(page) && page > 0 ? page : 1;
    const validatedLimit = Number.isFinite(limit) && limit > 0 ? Math.min(limit, 50) : 10;

    this.logger.log(
      `Fetching mobile notifications - userId: ${userId}, page: ${validatedPage}, limit: ${validatedLimit}, status: ${status}`,
    );

    return this.notificationsService.getNotifications({
      userId,
      page: validatedPage,
      limit: validatedLimit,
      status,
    });
  }

  @Public()
  @Get('unread-count')
  @ApiOperation({ summary: 'Get the count of unread notifications for a mobile user' })
  @ApiQuery({ name: 'userId', required: true, type: Number, description: 'ID of the recipient user' })
  async getUnreadCount(@Query('userId', ParseIntPipe) userId: number) {
    const count = await this.notificationsService.getUnreadCount(userId);
    return { success: true, unreadCount: count };
  }

  @Public()
  @Patch('read-all')
  @ApiOperation({ summary: 'Mark all notifications as read for a mobile user' })
  @ApiQuery({ name: 'userId', required: true, type: Number, description: 'ID of the recipient user' })
  async markAllAsRead(@Query('userId', ParseIntPipe) userId: number) {
    await this.notificationsService.markAllAsRead(userId);
    return { success: true, message: 'All notifications marked as read' };
  }

  @Public()
  @Patch(':id/read')
  @ApiOperation({ summary: 'Mark a specific notification as read' })
  @ApiParam({ name: 'id', required: true, type: Number, description: 'Notification ID' })
  @ApiQuery({ name: 'userId', required: true, type: Number, description: 'ID of the recipient user' })
  async markAsRead(
    @Param('id', ParseIntPipe) id: number,
    @Query('userId', ParseIntPipe) userId: number,
  ) {
    const success = await this.notificationsService.markAsRead(id, userId);
    if (!success) {
      throw new BadRequestException('Notification not found or access denied');
    }
    return { success: true, message: 'Notification marked as read' };
  }
}
