import { ApiTags, ApiOperation, ApiResponse } from '@nestjs/swagger';
import { Controller, Post, Body, HttpCode, HttpStatus, Req } from '@nestjs/common';
import { AuthService } from './auth.service';
import { AppleLoginDto, DevLoginDto, RefreshDto } from './dto';
import { LoginResponseDto, RefreshResponseDto, LogoutResponseDto } from './dto/auth-response.dto';
import { Public } from '../../common/decorators/public.decorator';
import { LoginRateLimit } from '../../common/decorators/rate-limit.decorator';
import type { Request } from 'express';

@ApiTags('auth')
@Controller('auth')
export class AuthController {
  constructor(private readonly authService: AuthService) {}

  @Public()
  @Post('dev-login')
  @HttpCode(HttpStatus.OK)
  @LoginRateLimit()
  @ApiOperation({ summary: '开发登录（仅非生产环境）' })
  @ApiResponse({ status: 200, description: '登录成功', type: LoginResponseDto })
  @ApiResponse({ status: 403, description: '生产环境禁用' })
  async devLogin(@Body() dto: DevLoginDto) {
    return this.authService.devLogin(dto);
  }

  @Public()
  @Post('apple')
  @HttpCode(HttpStatus.OK)
  @LoginRateLimit()
  @ApiOperation({ summary: 'Apple 登录' })
  @ApiResponse({ status: 200, description: '登录成功', type: LoginResponseDto })
  @ApiResponse({ status: 401, description: '身份验证失败' })
  async appleLogin(@Body() dto: AppleLoginDto) {
    return this.authService.appleLogin(dto);
  }

  @Public()
  @Post('refresh')
  @HttpCode(HttpStatus.OK)
  @ApiOperation({ summary: '刷新令牌' })
  @ApiResponse({ status: 200, description: '刷新成功', type: RefreshResponseDto })
  @ApiResponse({ status: 401, description: '刷新令牌无效' })
  async refresh(@Body() dto: RefreshDto) {
    return this.authService.refresh(dto.refreshToken);
  }

  @Post('logout')
  @HttpCode(HttpStatus.OK)
  @ApiOperation({ summary: '退出登录' })
  @ApiResponse({ status: 200, description: '退出成功', type: LogoutResponseDto })
  @ApiResponse({ status: 401, description: '未登录' })
  async logout(@Req() req: Request, @Body() dto: RefreshDto) {
    const user = (req as any).user;
    await this.authService.logout(user.id, dto.refreshToken);
    return { success: true, message: '已退出登录' };
  }
}
