import { Body, Controller, Delete, Get, Param, Patch, Post, UseGuards } from '@nestjs/common';
import { ApiBearerAuth, ApiSecurity, ApiTags } from '@nestjs/swagger';
import { CurrentPrincipal } from '../auth/decorators/current-user.decorator';
import { Roles } from '../auth/decorators/roles.decorator';
import { JwtAuthGuard, UserOrApiKeyGuard } from '../auth/guards/auth.guard';
import { OrgRolesGuard } from '../auth/guards/org-roles.guard';
import { ScopesGuard } from '../auth/guards/scopes.guard';
import { UserPrincipal } from '../auth/principal';
import { AddMemberDto, UpdateMemberDto, UpdateOrgDto } from './dto/orgs.dto';
import { OrgsService } from './orgs.service';

@ApiTags('orgs')
@Controller('orgs')
export class OrgsController {
  constructor(private readonly orgsService: OrgsService) {}

  @Get()
  @UseGuards(JwtAuthGuard)
  @ApiBearerAuth('jwt')
  listMine(@CurrentPrincipal() principal: UserPrincipal) {
    return this.orgsService.listForUser(principal.userId);
  }

  @Patch(':orgId')
  @UseGuards(JwtAuthGuard, OrgRolesGuard)
  @Roles('ORG_ADMIN')
  @ApiBearerAuth('jwt')
  rename(@Param('orgId') orgId: string, @Body() dto: UpdateOrgDto) {
    return this.orgsService.rename(orgId, dto.name);
  }

  @Get(':orgId/members')
  @UseGuards(UserOrApiKeyGuard, OrgRolesGuard, ScopesGuard)
  @ApiBearerAuth('jwt')
  @ApiSecurity('apiKey')
  listMembers(@Param('orgId') orgId: string) {
    return this.orgsService.listMembers(orgId);
  }

  @Post(':orgId/members')
  @UseGuards(JwtAuthGuard, OrgRolesGuard)
  @Roles('ORG_ADMIN')
  @ApiBearerAuth('jwt')
  addMember(@Param('orgId') orgId: string, @Body() dto: AddMemberDto) {
    return this.orgsService.addMember(orgId, dto.email, dto.role);
  }

  @Patch(':orgId/members/:userId')
  @UseGuards(JwtAuthGuard, OrgRolesGuard)
  @Roles('ORG_ADMIN')
  @ApiBearerAuth('jwt')
  updateMember(
    @Param('orgId') orgId: string,
    @Param('userId') userId: string,
    @Body() dto: UpdateMemberDto,
  ) {
    return this.orgsService.updateMember(orgId, userId, dto.role);
  }

  @Delete(':orgId/members/:userId')
  @UseGuards(JwtAuthGuard, OrgRolesGuard)
  @Roles('ORG_ADMIN')
  @ApiBearerAuth('jwt')
  removeMember(@Param('orgId') orgId: string, @Param('userId') userId: string) {
    return this.orgsService.removeMember(orgId, userId);
  }
}
