import { Controller, Post, Get, Body, Req, HttpCode, HttpStatus } from '@nestjs/common';
import { ApiTags, ApiOperation, ApiBearerAuth, ApiProperty } from '@nestjs/swagger';
import { IsString, IsNotEmpty } from 'class-validator';
import { AuthService } from '../../application/services/auth.service';
import { Public } from '../../shared/guards/admin-auth.guard';
import { getClientIp } from '../../shared/utils/get-client-ip';

class LoginDto {
  @ApiProperty({ description: '用户名' })
  @IsString()
  @IsNotEmpty()
  username: string;

  @ApiProperty({ description: '密码' })
  @IsString()
  @IsNotEmpty()
  password: string;
}

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

  @Post('login')
  @Public()
  @HttpCode(HttpStatus.OK)
  @ApiOperation({ summary: '管理员登录' })
  async login(@Body() dto: LoginDto, @Req() req: any) {
    return this.authService.login(dto.username, dto.password, getClientIp(req), req.headers['user-agent']);
  }

  @Get('profile')
  @ApiBearerAuth()
  @ApiOperation({ summary: '获取当前用户信息' })
  async getProfile(@Req() req: any) {
    return {
      id: req.admin.id,
      username: req.admin.username,
      role: req.admin.role,
    };
  }

  @Post('logout')
  @ApiBearerAuth()
  @HttpCode(HttpStatus.OK)
  @ApiOperation({ summary: '退出登录' })
  async logout(@Req() req: any) {
    await this.authService.logout(req.admin.id, getClientIp(req), req.headers['user-agent']);
    return { success: true };
  }
}
