import { Body, Controller, Get, Post, Req, UseGuards } from '@nestjs/common';
import { OperationLog } from '../audit/operation-log.decorator';
import { AuthService } from './auth.service';
import { AuthGuard } from './auth.guard';
import type { ChangePasswordDto, LoginDto, RegisterDto } from './dto/login.dto';
import type { AuthenticatedRequest } from './types/authenticated-request';
import type { Request } from 'express';

@Controller('api/user')
export class AuthController {
  constructor(private readonly authService: AuthService) {}

  @Post('login')
  login(@Body() dto: LoginDto, @Req() request: Request) {
    return this.authService.login(dto, request);
  }

  @Post('register')
  @OperationLog({
    action: 'auth.register',
    resourceType: 'user',
    resourceIdFromResult: 'user.id',
    metadataFromBody: ['name', 'email'],
    description: '注册用户',
  })
  register(@Body() dto: RegisterDto) {
    return this.authService.register(dto);
  }

  @UseGuards(AuthGuard)
  @Post('change-password')
  @OperationLog({
    action: 'auth.change_password',
    resourceType: 'user',
    resourceIdFromResult: 'user.id',
    metadataFromBody: [],
    description: '修改密码',
  })
  changePassword(
    @Req() request: AuthenticatedRequest,
    @Body() dto: ChangePasswordDto,
  ) {
    return this.authService.changePassword(request.user, dto);
  }

  @UseGuards(AuthGuard)
  @Post('refresh-token')
  refreshToken(@Req() request: AuthenticatedRequest) {
    return this.authService.refreshToken(request.user);
  }

  @UseGuards(AuthGuard)
  @Post('logout')
  @OperationLog({
    action: 'auth.logout',
    resourceType: 'user',
    resourceIdFromResult: 'id',
    metadataFromBody: [],
    description: '退出登录',
  })
  logout(@Req() request: AuthenticatedRequest) {
    return this.authService.logout(request.user);
  }

  @UseGuards(AuthGuard)
  @Get('userInfo')
  userInfo(@Req() request: AuthenticatedRequest) {
    return this.authService.toUserInfo(request.user);
  }
}
