import {
  Controller,
  Get,
  HttpCode,
  HttpStatus,
  Param,
  ParseIntPipe,
  Patch,
  Query,
  Req,
  UseGuards,
} from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';
import { ApiBearerAuth, ApiTags } from '@nestjs/swagger';
import { TeamAccessService } from '../teams/team-access.service';
import { NotificationQueryDto } from './dto/notification-query.dto';
import { NotificationsService } from './notifications.service';

@ApiTags('Notifications')
@ApiBearerAuth()
@UseGuards(AuthGuard('jwt'))
@Controller({ path: 'teams', version: '1' })
export class NotificationsController {
  constructor(
    private readonly service: NotificationsService,
    private readonly access: TeamAccessService,
  ) {}

  @Get(':teamId/notifications')
  async list(
    @Req() req,
    @Param('teamId', ParseIntPipe) teamId: number,
    @Query() query: NotificationQueryDto,
  ) {
    await this.access.assertMember(Number(req.user.id), teamId);
    return this.service.listForUser(Number(req.user.id), teamId, query.page ?? 1, query.limit ?? 20);
  }

  @Get(':teamId/notifications/unread-count')
  async unreadCount(@Req() req, @Param('teamId', ParseIntPipe) teamId: number) {
    await this.access.assertMember(Number(req.user.id), teamId);
    return { count: await this.service.getUnreadCount(Number(req.user.id), teamId) };
  }

  @Patch(':teamId/notifications/:id/read')
  @HttpCode(HttpStatus.OK)
  async markRead(
    @Req() req,
    @Param('teamId', ParseIntPipe) teamId: number,
    @Param('id', ParseIntPipe) id: number,
  ) {
    await this.access.assertMember(Number(req.user.id), teamId);
    await this.service.markRead(id, Number(req.user.id));
  }

  @Patch(':teamId/notifications/read-all')
  @HttpCode(HttpStatus.OK)
  async markAllRead(@Req() req, @Param('teamId', ParseIntPipe) teamId: number) {
    await this.access.assertMember(Number(req.user.id), teamId);
    await this.service.markAllRead(Number(req.user.id), teamId);
  }
}
