import { Controller, Post, Get, Body, UseGuards, Req, Res } from '@nestjs/common';
import { ApiTags, ApiBearerAuth } from '@nestjs/swagger';
import { AuthGuard } from '@nestjs/passport';
import { Throttle } from '@nestjs/throttler';
import { AuthService } from './auth.service';
import { RegisterDto } from './dto/register.dto';
import { LoginDto } from './dto/login.dto';

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

  private setTokenCookie(res: any, accessToken: string) {
    const isProd = process.env.NODE_ENV === 'production';
    res.cookie('token', accessToken, {
      httpOnly: true,
      secure: isProd,
      sameSite: 'lax',
      path: '/',
      maxAge: 7 * 24 * 60 * 60 * 1000,
    });
  }

  @Post('register')
  @Throttle({ default: { limit: 3, ttl: 60000 } })
  async register(@Body() body: RegisterDto, @Res({ passthrough: true }) res: any) {
    const tokens = await this.authService.register(body);
    this.setTokenCookie(res, tokens.accessToken);
    return tokens;
  }

  @Post('login')
  @Throttle({ default: { limit: 5, ttl: 60000 } })
  async login(@Body() body: LoginDto, @Res({ passthrough: true }) res: any) {
    const tokens = await this.authService.login(body.account, body.password);
    this.setTokenCookie(res, tokens.accessToken);
    return tokens;
  }

  @Post('refresh')
  @Throttle({ default: { limit: 10, ttl: 60000 } })
  async refresh(@Body() body: { accessToken: string }, @Res({ passthrough: true }) res: any) {
    const tokens = await this.authService.refreshAccessToken(body.accessToken);
    this.setTokenCookie(res, tokens.accessToken);
    return tokens;
  }

  @Get('profile')
  @UseGuards(AuthGuard('jwt'))
  @ApiBearerAuth()
  async profile(@Req() req: any) {
    return this.authService.getProfile(req.user.userId);
  }

  @Get('verify')
  @UseGuards(AuthGuard('jwt'))
  async verify(@Req() req: any) {
    const profile = await this.authService.getProfile(req.user.userId);
    return { ...profile, accessToken: req.headers.authorization?.replace('Bearer ', '') || '' };
  }

  @Post('logout')
  async logout(@Res({ passthrough: true }) res: any) {
    res.cookie('token', '', { httpOnly: true, maxAge: 0, path: '/' });
    return { message: '已退出' };
  }
}
