import {
  Controller,
  Post,
  Body,
  HttpCode,
  HttpStatus,
  UseGuards,
} from '@nestjs/common';
import { ThrottlerGuard } from '@nestjs/throttler';
import { IsString, IsNotEmpty, IsEnum, Matches } from 'class-validator';
import { SmsService } from '@/application/services';
import { SmsVerificationType } from '@/domain';

class SendSmsDto {
  @IsString()
  @IsNotEmpty({ message: '手机号不能为空' })
  @Matches(/^1[3-9]\d{9}$/, { message: '手机号格式不正确' })
  phone: string;

  @IsEnum(SmsVerificationType, { message: '验证码类型无效' })
  type: SmsVerificationType;
}

class VerifySmsDto {
  @IsString()
  @IsNotEmpty({ message: '手机号不能为空' })
  @Matches(/^1[3-9]\d{9}$/, { message: '手机号格式不正确' })
  phone: string;

  @IsString()
  @IsNotEmpty({ message: '验证码不能为空' })
  @Matches(/^\d{6}$/, { message: '验证码格式不正确' })
  code: string;

  @IsEnum(SmsVerificationType, { message: '验证码类型无效' })
  type: SmsVerificationType;
}

@Controller('auth/sms')
@UseGuards(ThrottlerGuard)
export class SmsController {
  constructor(private readonly smsService: SmsService) {}

  /**
   * 发送验证码
   * POST /sms/send
   */
  @Post('send')
  @HttpCode(HttpStatus.OK)
  async sendCode(
    @Body() dto: SendSmsDto,
  ): Promise<{ success: boolean; data: { expiresIn: number } }> {
    const result = await this.smsService.sendCode({
      phone: dto.phone,
      type: dto.type as SmsVerificationType,
    });

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

  /**
   * 验证验证码
   * POST /sms/verify
   */
  @Post('verify')
  @HttpCode(HttpStatus.OK)
  async verifyCode(
    @Body() dto: VerifySmsDto,
  ): Promise<{ success: boolean; data: { valid: boolean } }> {
    const valid = await this.smsService.verifyCode({
      phone: dto.phone,
      code: dto.code,
      type: dto.type as SmsVerificationType,
    });

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