import { Controller, Post, Body, Get, Request, Req } from '@nestjs/common';
import { AuthService } from './auth.service';
import { LoginDto } from './dto/auth.dto';
import { OperationLogsService } from '../operation-logs/operation-logs.service';
import { extractRequestInfo } from '../common/request-utils';
import { Throttle } from '@nestjs/throttler';
import { Public } from './decorators/public.decorator';
import { Authenticated } from './decorators/authenticated.decorator';

@Controller('auth')
export class AuthController {
  constructor(
    private authService: AuthService,
    private logService: OperationLogsService,
  ) {}

  @Public()
  @Post('login')
  @Throttle({ default: { ttl: 60000, limit: 5 } })
  async login(@Body() dto: LoginDto, @Req() req: any) {
    const { ipAddress, userAgent } = extractRequestInfo(req);
    try {
      const result = await this.authService.login(dto, ipAddress);
      await this.logService.log({
        userId: result.user.id,
        username: result.user.username,
        module: '认证',
        action: '登录成功',
        ipAddress,
        userAgent,
        status: 'success',
      });
      return result;
    } catch (e: any) {
      await this.logService.log({
        username: dto.username,
        module: '认证',
        action: '登录失败',
        detail: e.message || '密码错误',
        ipAddress,
        userAgent,
        status: 'fail',
      });
      throw e;
    }
  }

  @Authenticated()
  @Get('profile')
  getProfile(@Request() req: any) {
    return req.user;
  }
}
