import { Controller, Post, Body, Get, Param, Put } from '@nestjs/common';
import { ApiTags, ApiOperation, ApiResponse } from '@nestjs/swagger';
import { AddressDerivationService } from '@/application/services/address-derivation.service';
import { MnemonicVerificationService } from '@/application/services/mnemonic-verification.service';
import { MnemonicDerivationAdapter } from '@/infrastructure/blockchain';
import { DeriveAddressDto, VerifyMnemonicDto, VerifyMnemonicHashDto, MarkMnemonicBackupDto, RevokeMnemonicDto } from '../dto/request';
import { DeriveAddressResponseDto } from '../dto/response';

/**
 * 内部 API 控制器
 * 供其他微服务调用
 */
@ApiTags('Internal')
@Controller('internal')
export class InternalController {
  constructor(
    private readonly addressDerivationService: AddressDerivationService,
    private readonly mnemonicVerification: MnemonicVerificationService,
    private readonly mnemonicDerivation: MnemonicDerivationAdapter,
  ) {}

  @Post('derive-address')
  @ApiOperation({ summary: '从公钥派生地址' })
  @ApiResponse({ status: 201, description: '派生成功', type: DeriveAddressResponseDto })
  async deriveAddress(@Body() dto: DeriveAddressDto): Promise<DeriveAddressResponseDto> {
    const result = await this.addressDerivationService.deriveAndRegister({
      userId: BigInt(dto.userId),
      accountSequence: dto.accountSequence,
      publicKey: dto.publicKey,
    });

    return {
      userId: result.userId.toString(),
      publicKey: result.publicKey,
      addresses: result.addresses.map((a) => ({
        chainType: a.chainType,
        address: a.address,
      })),
    };
  }

  @Get('user/:userId/addresses')
  @ApiOperation({ summary: '获取用户的所有地址' })
  async getUserAddresses(@Param('userId') userId: string) {
    const addresses = await this.addressDerivationService.getUserAddresses(BigInt(userId));
    return {
      userId,
      addresses: addresses.map((a) => ({
        chainType: a.chainType.toString(),
        address: a.address.toString(),
        isActive: a.isActive,
      })),
    };
  }

  @Post('verify-mnemonic')
  @ApiOperation({ summary: '验证助记词是否匹配指定地址' })
  @ApiResponse({ status: 200, description: '验证结果' })
  async verifyMnemonic(@Body() dto: VerifyMnemonicDto) {
    const result = this.mnemonicDerivation.verifyMnemonic(dto.mnemonic, dto.expectedAddresses);
    return {
      valid: result.valid,
      matchedAddresses: result.matchedAddresses,
      mismatchedAddresses: result.mismatchedAddresses,
    };
  }

  @Post('derive-from-mnemonic')
  @ApiOperation({ summary: '从助记词派生所有链地址' })
  @ApiResponse({ status: 200, description: '派生的地址列表' })
  async deriveFromMnemonic(@Body() dto: { mnemonic: string }) {
    const addresses = this.mnemonicDerivation.deriveAllAddresses(dto.mnemonic);
    return {
      addresses: addresses.map((a) => ({
        chainType: a.chainType,
        address: a.address,
      })),
    };
  }

  @Post('verify-mnemonic-hash')
  @ApiOperation({ summary: '通过账户序列号验证助记词' })
  @ApiResponse({ status: 200, description: '验证结果' })
  async verifyMnemonicHash(@Body() dto: VerifyMnemonicHashDto) {
    const result = await this.mnemonicVerification.verifyMnemonicByAccount({
      accountSequence: dto.accountSequence,
      mnemonic: dto.mnemonic,
    });
    return {
      valid: result.valid,
      message: result.message,
    };
  }

  @Put('mnemonic/backup')
  @ApiOperation({ summary: '标记助记词已备份' })
  @ApiResponse({ status: 200, description: '标记成功' })
  async markMnemonicBackedUp(@Body() dto: MarkMnemonicBackupDto) {
    await this.mnemonicVerification.markAsBackedUp(dto.accountSequence);
    return {
      success: true,
      message: 'Mnemonic marked as backed up',
    };
  }

  @Post('mnemonic/revoke')
  @ApiOperation({ summary: '挂失助记词' })
  @ApiResponse({ status: 200, description: '挂失结果' })
  async revokeMnemonic(@Body() dto: RevokeMnemonicDto) {
    const result = await this.mnemonicVerification.revokeMnemonic(dto.accountSequence, dto.reason);
    return result;
  }
}
