import {
  Body,
  Controller,
  DefaultValuePipe,
  Delete,
  Get,
  HttpCode,
  HttpStatus,
  Param,
  ParseIntPipe,
  ParseUUIDPipe,
  Post,
  Query,
  UseGuards,
} from '@nestjs/common';
import { ApiOperation, ApiResponse, ApiTags } from '@nestjs/swagger';
import { Throttle } from '@nestjs/throttler';
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 {
  AiService,
  type ConversationDetail,
  type ConversationSummary,
  type SendResult,
} from './ai.service';
import { SendMessageDto } from './dto/send-message.dto';

// AI 채팅 컨트롤러 — 인증 필요. 대화는 본인 소유만 접근(서비스에서 스코프).
@ApiTags('AI')
@Controller('ai/conversations')
@UseGuards(JwtAuthGuard)
export class AiController {
  constructor(private readonly aiService: AiService) {}

  @Get()
  @ApiOperation({ summary: '내 대화 목록 (최근순, 페이지네이션)' })
  @ApiResponse({ status: 200, description: '목록 조회 성공' })
  list(
    @CurrentUser() user: PublicUser,
    @Query('page', new DefaultValuePipe(1), ParseIntPipe) page: number,
    @Query('size', new DefaultValuePipe(20), ParseIntPipe) size: number,
  ): Promise<PaginatedResult<ConversationSummary>> {
    return this.aiService.listConversations(user.id, page, size);
  }

  @Get(':id')
  @ApiOperation({ summary: '대화 상세 (메시지 포함)' })
  @ApiResponse({ status: 200, description: '조회 성공' })
  @ApiResponse({ status: 404, description: '대화 없음 (RES_001)' })
  get(
    @CurrentUser() user: PublicUser,
    @Param('id', ParseUUIDPipe) id: string,
  ): Promise<ConversationDetail> {
    return this.aiService.getConversation(user.id, id);
  }

  @Post()
  @HttpCode(HttpStatus.CREATED)
  @Throttle({ default: { limit: 1000, ttl: 60_000 } })
  @ApiOperation({ summary: '새 대화 시작 (첫 메시지)' })
  @ApiResponse({ status: 201, description: '생성 + AI 응답' })
  start(
    @CurrentUser() user: PublicUser,
    @Body() dto: SendMessageDto,
  ): Promise<SendResult> {
    return this.aiService.startConversation(user.id, dto.content);
  }

  @Post(':id/messages')
  @HttpCode(HttpStatus.OK)
  @Throttle({ default: { limit: 1000, ttl: 60_000 } })
  @ApiOperation({ summary: '대화에 메시지 추가' })
  @ApiResponse({ status: 200, description: 'AI 응답' })
  @ApiResponse({ status: 404, description: '대화 없음 (RES_001)' })
  send(
    @CurrentUser() user: PublicUser,
    @Param('id', ParseUUIDPipe) id: string,
    @Body() dto: SendMessageDto,
  ): Promise<SendResult> {
    return this.aiService.addMessage(user.id, id, dto.content);
  }

  @Delete(':id')
  @HttpCode(HttpStatus.OK)
  @ApiOperation({ summary: '대화 삭제' })
  @ApiResponse({ status: 200, description: '삭제 성공' })
  @ApiResponse({ status: 404, description: '대화 없음 (RES_001)' })
  async remove(
    @CurrentUser() user: PublicUser,
    @Param('id', ParseUUIDPipe) id: string,
  ): Promise<null> {
    await this.aiService.deleteConversation(user.id, id);
    return null;
  }
}
