import {
  Body,
  Controller,
  Delete,
  Get,
  HttpCode,
  HttpStatus,
  Param,
  ParseUUIDPipe,
  Patch,
  Post,
  UseGuards,
} from '@nestjs/common';
import {
  ApiOperation,
  ApiResponse,
  ApiTags,
  ApiBearerAuth,
} 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 {
  MeetingService,
  type MeetingTokenResult,
  type MeetingRoomResponse,
} from './meeting.service';
import { CreateMeetingTokenDto } from './dto/create-meeting-token.dto';
import { CreateMeetingRoomDto } from './dto/create-meeting-room.dto';
import { UpdateMeetingRoomDto } from './dto/update-meeting-room.dto';

// 화상회의 컨트롤러 — 방 관리 + LiveKit 입장 토큰 발급(인증 필요).
@ApiTags('화상회의')
@ApiBearerAuth()
@UseGuards(JwtAuthGuard)
@Controller('meetings')
export class MeetingController {
  constructor(private readonly meetingService: MeetingService) {}

  @Get('rooms')
  @ApiOperation({ summary: '회의 방 목록' })
  @ApiResponse({ status: 200, description: '목록 조회 성공' })
  listRooms(@CurrentUser() user: PublicUser): Promise<MeetingRoomResponse[]> {
    return this.meetingService.listRooms(user.id);
  }

  @Post('rooms')
  @ApiOperation({ summary: '회의 방 생성(생성자=진행자)' })
  @ApiResponse({ status: 201, description: '생성 성공' })
  createRoom(
    @CurrentUser() user: PublicUser,
    @Body() dto: CreateMeetingRoomDto,
  ): Promise<MeetingRoomResponse> {
    return this.meetingService.createRoom(user.id, dto);
  }

  @Patch('rooms/:roomId')
  @ApiOperation({ summary: '회의 방 수정(진행자만)' })
  @ApiResponse({ status: 200, description: '수정 성공' })
  updateRoom(
    @CurrentUser() user: PublicUser,
    @Param('roomId', ParseUUIDPipe) roomId: string,
    @Body() dto: UpdateMeetingRoomDto,
  ): Promise<MeetingRoomResponse> {
    return this.meetingService.updateRoom(user.id, roomId, dto);
  }

  @Delete('rooms/:roomId')
  @HttpCode(HttpStatus.NO_CONTENT)
  @ApiOperation({ summary: '회의 방 삭제(진행자만)' })
  @ApiResponse({ status: 204, description: '삭제 성공' })
  async deleteRoom(
    @CurrentUser() user: PublicUser,
    @Param('roomId', ParseUUIDPipe) roomId: string,
  ): Promise<void> {
    await this.meetingService.deleteRoom(user.id, roomId);
  }

  @Post('token')
  @ApiOperation({ summary: 'LiveKit 입장 토큰 발급' })
  @ApiResponse({ status: 201, description: '토큰 발급 성공' })
  issueToken(
    @CurrentUser() user: PublicUser,
    @Body() dto: CreateMeetingTokenDto,
  ): Promise<MeetingTokenResult> {
    return this.meetingService.issueToken(user, dto.code);
  }
}
