import { Inject } from '@nestjs/common';
import { CommandHandler, type ICommandHandler } from '@nestjs/cqrs';
import { NotFoundException, CacheService, CachePrefix } from '@modules/shared';
import { USER_REPOSITORY, type IUserRepository } from '../../../domain/repositories/user.repository';
import { VerifyKycCommand } from './verify-kyc.command';

@CommandHandler(VerifyKycCommand)
export class VerifyKycHandler implements ICommandHandler<VerifyKycCommand> {
  constructor(
    @Inject(USER_REPOSITORY) private readonly userRepo: IUserRepository,
    private readonly cache: CacheService,
  ) {}

  async execute(command: VerifyKycCommand): Promise<void> {
    const user = await this.userRepo.findById(command.userId);
    if (!user) {
      throw new NotFoundException('Người dùng', command.userId);
    }

    user.updateKycStatus(command.kycStatus, command.kycData);
    await this.userRepo.update(user);

    await this.cache.invalidate(CacheService.buildKey(CachePrefix.USER_PROFILE, command.userId));
  }
}
