import { Injectable, Inject, NotFoundException } from '@nestjs/common';
import {
  AccountSequence,
  Phone,
  USER_REPOSITORY,
  UserRepository,
  SYNCED_LEGACY_USER_REPOSITORY,
  SyncedLegacyUserRepository,
} from '@/domain';

export interface UserProfileResult {
  accountSequence: string;
  phone: string;
  source: 'V1' | 'V2';
  status: string;
  kycStatus: string;
  realName?: string;
  createdAt?: Date;
  lastLoginAt?: Date;
}

@Injectable()
export class UserService {
  constructor(
    @Inject(USER_REPOSITORY)
    private readonly userRepository: UserRepository,
    @Inject(SYNCED_LEGACY_USER_REPOSITORY)
    private readonly syncedLegacyUserRepository: SyncedLegacyUserRepository,
  ) {}

  /**
   * 获取用户信息
   */
  async getProfile(accountSequence: string): Promise<UserProfileResult> {
    const user = await this.userRepository.findByAccountSequence(
      AccountSequence.create(accountSequence),
    );

    if (!user) {
      throw new NotFoundException('用户不存在');
    }

    return {
      accountSequence: user.accountSequence.value,
      phone: user.phone.value,
      source: user.source,
      status: user.status,
      kycStatus: user.kycStatus,
      realName: user.isKycVerified ? this.maskName(user.realName!) : undefined,
      createdAt: user.createdAt,
      lastLoginAt: user.lastLoginAt,
    };
  }

  /**
   * 根据手机号查找用户（用于P2P转账验证）
   * 先查 V2 users 表，未找到再查 synced_legacy_users 表
   */
  async lookupByPhone(phone: string): Promise<{ exists: boolean; accountSequence?: string; nickname?: string }> {
    const phoneVO = Phone.create(phone);

    // 1. 先查 V2 用户表
    const user = await this.userRepository.findByPhone(phoneVO);
    if (user && user.status === 'ACTIVE') {
      return {
        exists: true,
        accountSequence: user.accountSequence.value,
        nickname: user.isKycVerified ? this.maskName(user.realName!) : user.phone.masked,
      };
    }

    // 2. 查 1.0 同步用户表（未迁移的老用户）
    const legacyUser = await this.syncedLegacyUserRepository.findByPhone(phoneVO);
    if (legacyUser && legacyUser.status === 'ACTIVE' && !legacyUser.migratedToV2) {
      return {
        exists: true,
        accountSequence: legacyUser.accountSequence.value,
        nickname: legacyUser.nickname || legacyUser.phone.masked,
      };
    }

    return { exists: false };
  }

  /**
   * 更换手机号
   */
  async changePhone(accountSequence: string, newPhone: string): Promise<void> {
    const user = await this.userRepository.findByAccountSequence(
      AccountSequence.create(accountSequence),
    );

    if (!user) {
      throw new NotFoundException('用户不存在');
    }

    const phone = Phone.create(newPhone);

    // 检查新手机号是否已被使用
    const exists = await this.userRepository.existsByPhone(phone);
    if (exists) {
      throw new Error('手机号已被使用');
    }

    user.changePhone(phone);
    await this.userRepository.save(user);
  }

  /**
   * 脱敏姓名
   */
  private maskName(name: string): string {
    if (name.length <= 1) return name;
    return name[0] + '*'.repeat(name.length - 1);
  }
}
