import {
  Body,
  Controller,
  DefaultValuePipe,
  Delete,
  Get,
  HttpCode,
  HttpStatus,
  Param,
  ParseIntPipe,
  ParseUUIDPipe,
  Patch,
  Post,
  Query,
  UseGuards,
} from '@nestjs/common';
import { ApiOperation, ApiResponse, ApiTags } from '@nestjs/swagger';
import { JwtAuthGuard } from '../auth/guards/jwt-auth.guard';
import { CurrentUser } from '../auth/decorators/current-user.decorator';
import type { PublicUser } from '../user/user.service';
import type { PaginatedResult } from '../../common/pagination/pagination';
import {
  ProjectMemberService,
  type ProjectMemberResponse,
} from './project-member.service';
import { InviteProjectMemberDto } from './dto/invite-member.dto';
import { UpdateProjectMemberDto } from './dto/update-member.dto';

// 프로젝트 멤버 컨트롤러 — 모든 엔드포인트 인증 필요
@ApiTags('Project')
@Controller('projects/:projectId/members')
@UseGuards(JwtAuthGuard)
export class ProjectMemberController {
  constructor(private readonly memberService: ProjectMemberService) {}

  @Get()
  @ApiOperation({ summary: '프로젝트 멤버 목록 (페이지네이션)' })
  @ApiResponse({ status: 200, description: '목록 조회 성공' })
  list(
    @Param('projectId', ParseUUIDPipe) projectId: string,
    @Query('page', new DefaultValuePipe(1), ParseIntPipe) page: number,
    @Query('size', new DefaultValuePipe(20), ParseIntPipe) size: number,
  ): Promise<PaginatedResult<ProjectMemberResponse>> {
    return this.memberService.list(projectId, page, size);
  }

  @Post()
  @HttpCode(HttpStatus.CREATED)
  @ApiOperation({ summary: '멤버 초대 (admin)' })
  @ApiResponse({ status: 201, description: '초대 성공' })
  @ApiResponse({ status: 403, description: '권한 없음 (AUTH_003)' })
  @ApiResponse({ status: 409, description: '이미 멤버 (BIZ_001)' })
  invite(
    @Param('projectId', ParseUUIDPipe) projectId: string,
    @Body() dto: InviteProjectMemberDto,
    @CurrentUser() user: PublicUser,
  ): Promise<ProjectMemberResponse> {
    return this.memberService.invite(projectId, user.id, dto);
  }

  @Patch(':userId')
  @ApiOperation({ summary: '멤버 역할 변경 (admin, owner 제외)' })
  @ApiResponse({ status: 200, description: '변경 성공' })
  @ApiResponse({ status: 403, description: '권한 없음 / 소유자 변경 불가' })
  update(
    @Param('projectId', ParseUUIDPipe) projectId: string,
    @Param('userId', ParseUUIDPipe) userId: string,
    @Body() dto: UpdateProjectMemberDto,
    @CurrentUser() user: PublicUser,
  ): Promise<ProjectMemberResponse> {
    return this.memberService.update(projectId, user.id, userId, dto);
  }

  @Delete(':userId')
  @HttpCode(HttpStatus.OK)
  @ApiOperation({ summary: '멤버 제거 (admin, owner 제외)' })
  @ApiResponse({ status: 200, description: '제거 성공' })
  @ApiResponse({ status: 403, description: '권한 없음 / 소유자 제거 불가' })
  async remove(
    @Param('projectId', ParseUUIDPipe) projectId: string,
    @Param('userId', ParseUUIDPipe) userId: string,
    @CurrentUser() user: PublicUser,
  ): Promise<null> {
    await this.memberService.remove(projectId, user.id, userId);
    return null;
  }
}
