import { Controller, Get, Post, Request, UseGuards } from '@nestjs/common';
import { AuthService } from './auth.service';
import { LocalAuthGuard } from './local-auth.guard';
import { CombinedAuthGuard } from './combined-auth.guard';
import { Public } from './public.decorator';
import { ApiTags, ApiBearerAuth, ApiOperation, ApiResponse } from '@nestjs/swagger';

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

  @Public()
  @UseGuards(LocalAuthGuard)
  @Post('login')
  @ApiOperation({ summary: '用户登录', description: '使用用户名密码登录系统' })
  @ApiResponse({ status: 200, description: '登录成功，返回JWT token和用户信息' })
  @ApiResponse({ status: 401, description: '用户名或密码错误' })
  async login(@Request() req) {
    return this.authService.login(req.user);
  }

  @UseGuards(CombinedAuthGuard)
  @Get('profile')
  @ApiBearerAuth('JWT')
  @ApiOperation({ summary: '获取当前用户信息' })
  @ApiResponse({ status: 200, description: '返回当前用户信息' })
  @ApiResponse({ status: 401, description: '未授权' })
  getProfile(@Request() req) {
    return req.user;
  }

  @UseGuards(CombinedAuthGuard)
  @Get('api-key')
  @ApiBearerAuth('JWT')
  @ApiOperation({ summary: '获取当前用户的API Key' })
  @ApiResponse({ status: 200, description: '返回API Key' })
  async getApiKey(@Request() req) {
    const apiKey = await this.authService.getOrCreateApiKey(req.user.id);
    return { apiKey };
  }

  @UseGuards(CombinedAuthGuard)
  @Post('api-key/regenerate')
  @ApiBearerAuth('JWT')
  @ApiOperation({ summary: '重新生成API Key', description: '重新生成后旧的API Key将失效' })
  @ApiResponse({ status: 200, description: '返回新的API Key' })
  async regenerateApiKey(@Request() req) {
    const apiKey = await this.authService.regenerateApiKey(req.user.id);
    return { apiKey };
  }
}
