import {
  Controller,
  Get,
  Post,
  Put,
  Delete,
  Body,
  Param,
  Query,
  UseGuards,
  Request,
  ParseIntPipe,
} from '@nestjs/common';
import { ChatService } from './chat.service';
import { CreateGroupDto } from './dto/create-group.dto';
import { UpdateGroupDto } from './dto/update-group.dto';
import { AddMembersDto } from './dto/add-members.dto';
import { JwtAuthGuard } from '../auth/guards';

@Controller('live')
@UseGuards(JwtAuthGuard)
export class ChatController {
  constructor(private readonly chatService: ChatService) {}

  @Get()
  getChatInfo(): object {
    return {
      message: 'Chat API is running',
      websocketPath: '/api/live',
    };
  }

  // Gruppen-Verwaltung
  @Post('groups')
  createGroup(@Request() req, @Body() dto: CreateGroupDto) {
    return this.chatService.createGroup(req.user.sub, dto);
  }

  @Get('groups')
  getAllGroups() {
    return this.chatService.getAllGroups();
  }

  @Get('groups/my')
  getUserGroups(@Request() req) {
    return this.chatService.getUserGroups(req.user.sub);
  }

  @Get('groups/:id')
  getGroupById(@Param('id', ParseIntPipe) id: number) {
    return this.chatService.getGroupById(id);
  }

  @Put('groups/:id')
  updateGroup(
    @Param('id', ParseIntPipe) id: number,
    @Request() req,
    @Body() dto: UpdateGroupDto,
  ) {
    return this.chatService.updateGroup(id, req.user.sub, req.user.role, dto);
  }

  @Delete('groups/:id')
  deleteGroup(@Param('id', ParseIntPipe) id: number, @Request() req) {
    return this.chatService.deleteGroup(id, req.user.sub, req.user.role);
  }

  @Post('groups/:id/members')
  addMembers(
    @Param('id', ParseIntPipe) id: number,
    @Request() req,
    @Body() dto: AddMembersDto,
  ) {
    return this.chatService.addMembers(id, req.user.sub, req.user.role, dto);
  }

  @Delete('groups/:id/members/:userId')
  removeMember(
    @Param('id', ParseIntPipe) id: number,
    @Param('userId', ParseIntPipe) userId: number,
    @Request() req,
  ) {
    return this.chatService.removeMember(id, userId, req.user.sub, req.user.role);
  }

  // Nachrichten
  @Get('groups/:id/messages')
  getGroupMessages(
    @Param('id', ParseIntPipe) id: number,
    @Request() req,
    @Query('limit') limit?: number,
    @Query('offset') offset?: number,
  ) {
    return this.chatService.getGroupMessages(id, req.user.sub, limit, offset);
  }
}
