import {
  Controller,
  Post,
  Get,
  Put,
  Body,
  Param,
  Query,
  UseGuards,
  UseInterceptors,
  UploadedFile,
} from '@nestjs/common';
import { FileInterceptor } from '@nestjs/platform-express';
import {
  ApiTags,
  ApiOperation,
  ApiBearerAuth,
  ApiResponse,
  ApiConsumes,
  ApiBody,
  ApiProperty,
} from '@nestjs/swagger';
import { IsString, IsNotEmpty, Length, Matches } from 'class-validator';
import { KycApplicationService } from '@/application/services/kyc-application.service';
import {
  JwtAuthGuard,
  CurrentUser,
  CurrentUserData,
} from '@/shared/guards/jwt-auth.guard';

// ========== DTO 定义 ==========

class SubmitRealNameDto {
  @ApiProperty({ description: '真实姓名', example: '张三' })
  @IsString()
  @IsNotEmpty({ message: '姓名不能为空' })
  @Length(2, 50, { message: '姓名长度需在2-50个字符之间' })
  realName: string;

  @ApiProperty({ description: '身份证号码', example: '110101199001011234' })
  @IsString()
  @IsNotEmpty({ message: '身份证号不能为空' })
  @Matches(/^[1-9]\d{5}(18|19|20)\d{2}(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])\d{3}[\dXx]$/, {
    message: '身份证号格式不正确',
  })
  idCardNumber: string;
}

class InitFaceVerifyDto {
  metaInfo?: string;  // 客户端设备信息（阿里云 SDK 需要）
}

class QueryFaceVerifyDto {
  certifyId: string;
}

class UpdateKycConfigDto {
  level1Enabled?: boolean;  // 实名认证开关
  level2Enabled?: boolean;  // 实人认证开关
  level3Enabled?: boolean;  // KYC证件照开关
}

// ========== 用户端 KYC 控制器 ==========

@ApiTags('KYC - 用户认证')
@Controller('user/kyc')
@UseGuards(JwtAuthGuard)
@ApiBearerAuth()
export class KycController {
  constructor(private readonly kycService: KycApplicationService) {}

  /**
   * 获取 KYC 状态（包含三层认证详情）
   */
  @Get('status')
  @ApiOperation({
    summary: '获取 KYC 状态',
    description: '查询当前用户的三层认证状态和配置信息',
  })
  async getKycStatus(@CurrentUser() user: CurrentUserData) {
    const result = await this.kycService.getKycStatus(user.userId);
    return {
      code: 'OK',
      message: 'success',
      data: result,
    };
  }

  /**
   * 获取 KYC 配置（哪些层级开启）
   */
  @Get('config')
  @ApiOperation({
    summary: '获取 KYC 配置',
    description: '获取三层认证的开关状态',
  })
  async getKycConfig() {
    const result = await this.kycService.getKycConfig();
    return {
      code: 'OK',
      message: 'success',
      data: result,
    };
  }

  // ========== 层级1: 实名认证 ==========

  @Post('level1/submit')
  @ApiOperation({
    summary: '层级1: 提交实名认证',
    description: '提交姓名和身份证号进行二要素验证',
  })
  async submitRealName(
    @CurrentUser() user: CurrentUserData,
    @Body() dto: SubmitRealNameDto,
  ) {
    const result = await this.kycService.submitRealNameVerification(
      user.userId,
      dto.realName,
      dto.idCardNumber,
    );
    return {
      code: result.success ? 'OK' : 'FAILED',
      message: result.success ? '实名认证成功' : result.errorMessage,
      data: result,
    };
  }

  // ========== 层级2: 实人认证 ==========

  @Post('level2/init')
  @ApiOperation({
    summary: '层级2: 初始化实人认证',
    description: '初始化人脸活体检测，返回 certifyId 供客户端 SDK 使用',
  })
  async initFaceVerify(
    @CurrentUser() user: CurrentUserData,
    @Body() dto: InitFaceVerifyDto,
  ) {
    const result = await this.kycService.initFaceVerification(
      user.userId,
      dto.metaInfo,
    );
    return {
      code: 'OK',
      message: 'success',
      data: result,
    };
  }

  @Get('level2/query')
  @ApiOperation({
    summary: '层级2: 查询实人认证结果',
    description: '查询人脸活体检测结果',
  })
  async queryFaceVerify(
    @CurrentUser() user: CurrentUserData,
    @Query('certifyId') certifyId: string,
  ) {
    const result = await this.kycService.queryFaceVerification(
      user.userId,
      certifyId,
    );
    return {
      code: result.passed ? 'OK' : 'PENDING',
      message: result.passed ? '实人认证通过' : '认证结果待确认',
      data: result,
    };
  }

  // ========== 层级3: KYC 证件照 ==========

  @Post('level3/upload/:side')
  @UseInterceptors(FileInterceptor('file'))
  @ApiConsumes('multipart/form-data')
  @ApiOperation({
    summary: '层级3: 上传证件照',
    description: '上传身份证正面(front)或背面(back)照片',
  })
  @ApiBody({
    schema: {
      type: 'object',
      properties: {
        file: {
          type: 'string',
          format: 'binary',
        },
      },
    },
  })
  async uploadIdCard(
    @CurrentUser() user: CurrentUserData,
    @Param('side') side: 'front' | 'back',
    @UploadedFile() file: Express.Multer.File,
  ) {
    if (!['front', 'back'].includes(side)) {
      return {
        code: 'INVALID_PARAM',
        message: 'side 参数必须是 front 或 back',
      };
    }

    const result = await this.kycService.uploadIdCardPhoto(
      user.userId,
      side,
      file,
    );
    return {
      code: 'OK',
      message: '上传成功',
      data: result,
    };
  }

  @Post('level3/confirm')
  @ApiOperation({
    summary: '层级3: 确认提交 KYC',
    description: '确认完成证件照上传，提交 KYC 认证',
  })
  async confirmKycSubmission(@CurrentUser() user: CurrentUserData) {
    const result = await this.kycService.confirmKycSubmission(user.userId);
    return {
      code: 'OK',
      message: 'KYC认证完成',
      data: result,
    };
  }
}

// ========== 管理端 KYC 配置控制器 ==========

@ApiTags('KYC - 管理配置')
@Controller('admin/kyc')
export class AdminKycController {
  constructor(private readonly kycService: KycApplicationService) {}

  /**
   * 获取 KYC 配置
   */
  @Get('config')
  @ApiOperation({
    summary: '获取 KYC 配置',
    description: '获取三层认证的开关状态',
  })
  async getKycConfig() {
    const result = await this.kycService.getKycConfig();
    return {
      code: 'OK',
      message: 'success',
      data: result,
    };
  }

  /**
   * 更新 KYC 配置
   */
  @Put('config')
  @ApiOperation({
    summary: '更新 KYC 配置',
    description: '更新三层认证的开关状态',
  })
  async updateKycConfig(@Body() dto: UpdateKycConfigDto) {
    const result = await this.kycService.updateKycConfig(
      dto.level1Enabled,
      dto.level2Enabled,
      dto.level3Enabled,
      'admin',
    );
    return {
      code: 'OK',
      message: '配置已更新',
      data: result,
    };
  }
}
