import { Injectable, Inject, NotFoundException } from '@nestjs/common'; import { UserEntity, UserType } from '../domain/entities/user.entity'; import { IUserRepository, USER_REPOSITORY, } from '../domain/repositories/user.repository.interface'; @Injectable() export class UserService { constructor( @Inject(USER_REPOSITORY) private readonly userRepo: IUserRepository, ) {} async createAnonymousUser(fingerprint: string): Promise { // Check if user with this fingerprint already exists const existingUser = await this.userRepo.findByFingerprint(fingerprint); if (existingUser) { // Update last active time and return existing user existingUser.updateLastActive(); return this.userRepo.save(existingUser); } // Create new anonymous user const user = UserEntity.createAnonymous(fingerprint); return this.userRepo.save(user); } async findById(id: string): Promise { const user = await this.userRepo.findById(id); if (!user) { throw new NotFoundException('User not found'); } return user; } async findByFingerprint(fingerprint: string): Promise { return this.userRepo.findByFingerprint(fingerprint); } async findByPhone(phone: string): Promise { return this.userRepo.findByPhone(phone); } async upgradeToRegistered( userId: string, phone: string, ): Promise { const user = await this.findById(userId); // Check if phone is already registered const existingPhoneUser = await this.findByPhone(phone); if (existingPhoneUser && existingPhoneUser.id !== userId) { throw new Error('Phone number already registered'); } user.upgradeToRegistered(phone); return this.userRepo.save(user); } async updateLastActive(userId: string): Promise { await this.userRepo.updateLastActive(userId); } async updateProfile( userId: string, data: { nickname?: string; avatar?: string }, ): Promise { const user = await this.findById(userId); user.updateProfile(data); return this.userRepo.save(user); } }