import { Injectable, Inject } from '@nestjs/common';
import { GetMyProfileQuery } from './get-my-profile.query';
import {
  UserAccountRepository,
  USER_ACCOUNT_REPOSITORY,
} from '@/domain/repositories/user-account.repository.interface';
import { UserAccount } from '@/domain/aggregates/user-account/user-account.aggregate';
import { UserId } from '@/domain/value-objects';
import { ApplicationError } from '@/shared/exceptions/domain.exception';
import { UserProfileDTO } from '@/application/commands';

@Injectable()
export class GetMyProfileHandler {
  constructor(
    @Inject(USER_ACCOUNT_REPOSITORY)
    private readonly userRepository: UserAccountRepository,
  ) {}

  async execute(query: GetMyProfileQuery): Promise<UserProfileDTO> {
    const account = await this.userRepository.findById(
      UserId.create(query.userId),
    );
    if (!account) throw new ApplicationError('用户不存在');
    return this.toDTO(account);
  }

  private toDTO(account: UserAccount): UserProfileDTO {
    return {
      userId: account.userId.toString(),
      accountSequence: account.accountSequence.value,
      phoneNumber: account.phoneNumber?.masked() || null,
      nickname: account.nickname,
      avatarUrl: account.avatarUrl,
      referralCode: account.referralCode.value,
      walletAddresses: account.getAllWalletAddresses().map((wa) => ({
        chainType: wa.chainType,
        address: wa.address,
      })),
      kycStatus: account.kycStatus,
      kycInfo: account.kycInfo
        ? {
            realName: account.kycInfo.realName,
            idCardNumber: account.kycInfo.maskedIdCardNumber(),
          }
        : null,
      status: account.status,
      registeredAt: account.registeredAt,
      lastLoginAt: account.lastLoginAt,
    };
  }
}
