import {
  Controller,
  Post,
  Body,
  HttpCode,
  HttpStatus,
  UseGuards,
} from '@nestjs/common';
import { ThrottlerGuard } from '@nestjs/throttler';
import { IsString, IsNotEmpty, Matches, MinLength } from 'class-validator';
import { PasswordService } from '@/application/services';
import { JwtAuthGuard } from '@/shared/guards/jwt-auth.guard';
import { CapabilityGuard } from '@/shared/guards/capability.guard';
import { CurrentUser } from '@/shared/decorators/current-user.decorator';
import { RequireCapability } from '@/shared/decorators/require-capability.decorator';

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

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

  @IsString()
  @IsNotEmpty()
  @MinLength(6, { message: '密码至少6位' })
  newPassword: string;
}

class ChangePasswordDto {
  @IsString()
  @IsNotEmpty()
  oldPassword: string;

  @IsString()
  @IsNotEmpty()
  @MinLength(6, { message: '密码至少6位' })
  newPassword: string;
}

@Controller('auth/password')
@UseGuards(ThrottlerGuard)
export class PasswordController {
  constructor(private readonly passwordService: PasswordService) {}

  /**
   * 重置密码（通过短信验证码）
   * POST /password/reset
   */
  @Post('reset')
  @HttpCode(HttpStatus.OK)
  async resetPassword(
    @Body() dto: ResetPasswordDto,
  ): Promise<{ success: boolean }> {
    await this.passwordService.resetPassword(dto);
    return { success: true };
  }

  /**
   * 修改密码（需要登录）
   * POST /password/change
   */
  @Post('change')
  @HttpCode(HttpStatus.OK)
  @UseGuards(JwtAuthGuard, CapabilityGuard)
  @RequireCapability('PROFILE_EDIT')
  async changePassword(
    @CurrentUser() user: { accountSequence: string },
    @Body() dto: ChangePasswordDto,
  ): Promise<{ success: boolean }> {
    await this.passwordService.changePassword({
      accountSequence: user.accountSequence,
      oldPassword: dto.oldPassword,
      newPassword: dto.newPassword,
    });

    return { success: true };
  }
}
