import { Inject, InternalServerErrorException } from '@nestjs/common';
import { CommandHandler, type ICommandHandler } from '@nestjs/cqrs';
import { DomainException, LoggerService, 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,
    private readonly logger: LoggerService,
  ) {}

  async execute(command: VerifyKycCommand): Promise<void> {
    try {
      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));
    } catch (error) {
      if (error instanceof DomainException) throw error;
      this.logger.error(
        `Failed to verify KYC: ${error instanceof Error ? error.message : error}`,
        error instanceof Error ? error.stack : undefined,
        this.constructor.name,
      );
      throw new InternalServerErrorException('Không thể xác minh KYC cho người dùng');
    }
  }
}
