import { Injectable } from '@nestjs/common';
import { UserAccount } from '@/domain/aggregates/user-account/user-account.aggregate';
import { WalletAddress } from '@/domain/entities/wallet-address.entity';
import {
  DeviceInfo,
  KYCInfo,
  KYCStatus,
  AccountStatus,
  ChainType,
  AddressStatus,
} from '@/domain/value-objects';
import { UserAccountEntity } from '../entities/user-account.entity';
import { toMpcSignatureString } from '../entities/wallet-address.entity';

@Injectable()
export class UserAccountMapper {
  toDomain(entity: UserAccountEntity): UserAccount {
    const devices = (entity.devices || []).map((d) => {
      // 直接使用完整的 deviceInfo JSON，100% 保持原样
      return new DeviceInfo(
        d.deviceId,
        d.deviceName || '未命名设备',
        d.addedAt,
        d.lastActiveAt,
        d.deviceInfo || undefined,
      );
    });

    const wallets = (entity.walletAddresses || []).map((w) =>
      WalletAddress.reconstruct({
        addressId: w.addressId.toString(),
        userId: w.userId.toString(),
        chainType: w.chainType as ChainType,
        address: w.address,
        publicKey: w.publicKey,
        addressDigest: w.addressDigest,
        mpcSignature: toMpcSignatureString(w), // 64 bytes hex (r + s)
        status: w.status as AddressStatus,
        boundAt: w.boundAt,
      }),
    );

    const kycInfo =
      entity.realName && entity.idCardNumber
        ? KYCInfo.create({
            realName: entity.realName,
            idCardNumber: entity.idCardNumber,
            idCardFrontUrl: entity.idCardFrontUrl || '',
            idCardBackUrl: entity.idCardBackUrl || '',
          })
        : null;

    return UserAccount.reconstruct({
      userId: entity.userId.toString(),
      accountSequence: entity.accountSequence, // 现在是字符串类型
      devices,
      phoneNumber: entity.phoneNumber,
      nickname: entity.nickname,
      avatarUrl: entity.avatarUrl,
      inviterSequence: entity.inviterSequence, // 现在是字符串类型
      referralCode: entity.referralCode,
      walletAddresses: wallets,
      kycInfo,
      kycStatus: entity.kycStatus as KYCStatus,
      status: entity.status as AccountStatus,
      registeredAt: entity.registeredAt,
      lastLoginAt: entity.lastLoginAt,
      updatedAt: entity.updatedAt,
    });
  }
}
