import {
  Controller,
  Post,
  Body,
  HttpCode,
  HttpStatus,
  UseGuards,
  Req,
  Headers,
} from '@nestjs/common';
import { ThrottlerGuard } from '@nestjs/throttler';
import { AuthService, LoginResult } from '@/application/services';

class RegisterDto {
  phone: string;
  password: string;
  smsCode: string;
}

class LoginDto {
  phone: string;
  password: string;
}

class LoginBySmsDto {
  phone: string;
  smsCode: string;
}

class RefreshTokenDto {
  refreshToken: string;
}

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

  /**
   * 用户注册
   * POST /auth/register
   */
  @Post('register')
  async register(
    @Body() dto: RegisterDto,
    @Headers('X-Device-Info') deviceInfo?: string,
    @Req() req?: any,
  ): Promise<{ success: boolean; data: LoginResult }> {
    const result = await this.authService.register({
      phone: dto.phone,
      password: dto.password,
      smsCode: dto.smsCode,
    });

    return { success: true, data: result };
  }

  /**
   * 密码登录
   * POST /auth/login
   */
  @Post('login')
  @HttpCode(HttpStatus.OK)
  async login(
    @Body() dto: LoginDto,
    @Headers('X-Device-Info') deviceInfo?: string,
    @Req() req?: any,
  ): Promise<{ success: boolean; data: LoginResult }> {
    const ipAddress = req?.ip || req?.connection?.remoteAddress;
    const result = await this.authService.loginByPassword({
      phone: dto.phone,
      password: dto.password,
      deviceInfo,
      ipAddress,
    });

    return { success: true, data: result };
  }

  /**
   * 刷新令牌
   * POST /auth/refresh
   */
  @Post('refresh')
  @HttpCode(HttpStatus.OK)
  async refresh(
    @Body() dto: RefreshTokenDto,
  ): Promise<{ success: boolean; data: { accessToken: string; expiresIn: number } }> {
    const result = await this.authService.refreshToken(dto.refreshToken);
    return { success: true, data: result };
  }

  /**
   * 登出
   * POST /auth/logout
   */
  @Post('logout')
  @HttpCode(HttpStatus.OK)
  async logout(
    @Body() dto: RefreshTokenDto,
  ): Promise<{ success: boolean }> {
    await this.authService.logout(dto.refreshToken);
    return { success: true };
  }
}
