import {
  Controller,
  Get,
  Param,
  UseGuards,
  Query,
  HttpStatus,
  HttpCode,
  Request,
  ForbiddenException,
  ParseIntPipe,
} from '@nestjs/common';
import { UsersService } from './users.service';
import { ApiBearerAuth, ApiTags } from '@nestjs/swagger';
import { Roles } from 'src/roles/roles.decorator';
import { RoleEnum } from 'src/roles/roles.enum';
import { AuthGuard } from '@nestjs/passport';
import { RolesGuard } from 'src/roles/roles.guard';
import { UserDirectoryQueryDto } from './dto/user-directory-query.dto';
import { User } from './entities/user.entity';

@ApiBearerAuth()
@UseGuards(AuthGuard('jwt'), RolesGuard)
@ApiTags('Users')
@Controller({
  path: 'users',
  version: '1',
})
export class UsersController {
  constructor(private readonly usersService: UsersService) {}

  @Roles([RoleEnum.user, RoleEnum.admin])
  @Get('directory')
  @HttpCode(HttpStatus.OK)
  findDirectory(
    @Request() request: { user: Pick<User, 'id' | 'role'> },
    @Query() query: UserDirectoryQueryDto,
  ) {
    return this.usersService.findDirectory(request.user, query);
  }

  @Roles([RoleEnum.user, RoleEnum.admin])
  @Get(':id/teams')
  @HttpCode(HttpStatus.OK)
  findTeamsOfPlayer(
    @Request() request: { user: Pick<User, 'id' | 'role'> },
    @Param('id', ParseIntPipe) id: number,
  ) {
    if (request.user.id !== id) {
      throw new ForbiddenException('Users may only load their own teams');
    }
    return this.usersService.findMyTeams(id);
  }
}
