import { Controller, Get, Put, Param, Body, Query, UseGuards } from '@nestjs/common';
import { ApiTags, ApiBearerAuth, ApiOperation, ApiQuery } from '@nestjs/swagger';
import { ChatService } from './chat.service';
import { FlagMessageDto } from './dto/flag-message.dto';
import { CurrentTenant } from '../../common/decorators/current-tenant.decorator';
import { CurrentUser } from '../../common/decorators/current-user.decorator';
import { RequirePermission } from '../../common/decorators/require-permission.decorator';
import { JwtAuthGuard } from '../../common/guards/jwt-auth.guard';
import { PermissionsGuard } from '../../common/guards/permissions.guard';

@ApiTags('Chat')
@ApiBearerAuth()
@Controller('chat')
@UseGuards(JwtAuthGuard, PermissionsGuard)
export class ChatController {
  constructor(private readonly chatService: ChatService) {}

  @Get()
  @RequirePermission('chat.view')
  @ApiOperation({ summary: 'Get recent chat messages' })
  @ApiQuery({ name: 'limit', required: false, example: 100 })
  async getMessages(
    @CurrentTenant() licenseId: string,
    @Query('limit') limit?: string,
  ) {
    const limitNum = limit ? parseInt(limit, 10) : 100;
    return await this.chatService.getMessages(licenseId, limitNum);
  }

  @Put(':id/flag')
  @RequirePermission('chat.moderate')
  @ApiOperation({ summary: 'Flag or unflag a chat message' })
  async flagMessage(
    @CurrentTenant() licenseId: string,
    @CurrentUser('sub') userId: string,
    @Param('id') messageId: string,
    @Body() dto: FlagMessageDto,
  ) {
    return await this.chatService.flagMessage(licenseId, messageId, userId, dto);
  }
}
