import { Controller, Get, Param, Patch, Query, Req, UseGuards } from '@nestjs/common';
import { Request } from 'express';
import { ApiBearerAuth, ApiTags } from '@nestjs/swagger';
import { CurrentUser } from '../../common/decorators/current-user.decorator';
import { SuperAdminPermissions } from '../../common/decorators/superadmin-permissions.decorator';
import { JwtAuthGuard } from '../../common/guards/jwt-auth.guard';
import { SuperAdminJwtAuthGuard } from '../../common/guards/super-admin-jwt-auth.guard';
import { SuperAdminPermissionsGuard } from '../../common/guards/superadmin-permissions.guard';
import { JwtPayload } from '../../common/interfaces/jwt-payload.interface';
import { SUPERADMIN_PERMISSIONS } from '../superadmin/superadmin-permissions';
import {
  NotificationQueryDto,
  NotificationUnreadCountQueryDto,
} from './dto/notification-query.dto';
import { NotificationsService } from './notifications.service';
import { NotificationServiceClient } from './notification-service.client';

@ApiTags('Notifications')
@ApiBearerAuth()
@Controller('notifications')
export class NotificationsController {
  constructor(
    private readonly notificationsService: NotificationsService,
    private readonly notificationClient: NotificationServiceClient,
  ) {}

  @ApiBearerAuth()
  @UseGuards(SuperAdminJwtAuthGuard, SuperAdminPermissionsGuard)
  @SuperAdminPermissions(SUPERADMIN_PERMISSIONS.NOTIFICATIONS_READ)
  @Get('superadmin')
  async getForSuperAdmin(@Query() query: NotificationQueryDto) {
    return this.notificationsService.getForSuperAdmin(query);
  }

  @UseGuards(JwtAuthGuard)
  @Get()
  async getMine(
    @CurrentUser() user: JwtPayload,
    @Query() query: NotificationQueryDto,
    @Req() request: Request,
  ) {
    return this.notificationClient.getMine(user.sub, query, this.requestId(request));
  }

  @UseGuards(JwtAuthGuard)
  @Get('unread-count')
  async getUnreadCount(
    @CurrentUser() user: JwtPayload,
    @Query() query: NotificationUnreadCountQueryDto,
    @Req() request: Request,
  ) {
    return this.notificationClient.getUnreadCount(user.sub, query.category, this.requestId(request));
  }

  @UseGuards(JwtAuthGuard)
  @Get('unread-counts')
  async getUnreadCounts(@CurrentUser() user: JwtPayload) {
    return this.notificationsService.getUnreadCounts(user.sub);
  }

  @UseGuards(JwtAuthGuard)
  @Patch('read-all')
  async markAllRead(@CurrentUser() user: JwtPayload, @Req() request: Request) {
    return this.notificationClient.markAllRead(user.sub, this.requestId(request));
  }

  @UseGuards(JwtAuthGuard)
  @Patch(':id/read')
  async markRead(
    @CurrentUser() user: JwtPayload,
    @Param('id') notificationId: string,
    @Req() request: Request,
  ) {
    return this.notificationClient.markRead(user.sub, notificationId, this.requestId(request));
  }

  private requestId(request: Request): string | undefined {
    const value = request.headers['x-request-id'];
    return typeof value === 'string' ? value : undefined;
  }
}
