import { Inject, InternalServerErrorException } from '@nestjs/common';
import { CommandHandler, EventBus, type ICommandHandler } from '@nestjs/cqrs';
import { USER_REPOSITORY, type IUserRepository } from '@modules/auth';
import { DomainException, NotFoundException, ValidationException, LoggerService } from '@modules/shared';
import { KycApprovedEvent } from '../../../domain/events/kyc-approved.event';
import { ApproveKycCommand } from './approve-kyc.command';

export interface ApproveKycResult {
  userId: string;
  kycStatus: string;
  message: string;
}

@CommandHandler(ApproveKycCommand)
export class ApproveKycHandler implements ICommandHandler<ApproveKycCommand> {
  constructor(
    @Inject(USER_REPOSITORY) private readonly userRepo: IUserRepository,
    private readonly eventBus: EventBus,
    private readonly logger: LoggerService,
  ) {}

  async execute(command: ApproveKycCommand): Promise<ApproveKycResult> {
    try {
      const user = await this.userRepo.findById(command.userId);
      if (!user) {
        throw new NotFoundException('Người dùng không tồn tại');
      }

      if (user.kycStatus !== 'PENDING') {
        throw new ValidationException(
          `KYC đang ở trạng thái ${user.kycStatus}, chỉ có thể duyệt KYC đang chờ`,
          { currentStatus: user.kycStatus },
        );
      }

      user.updateKycStatus('VERIFIED');
      await this.userRepo.update(user);

      this.eventBus.publish(new KycApprovedEvent(user.id, command.adminId, command.comments));

      return {
        userId: user.id,
        kycStatus: 'VERIFIED',
        message: 'KYC đã được duyệt thành công',
      };
    } catch (error) {
      if (error instanceof DomainException) throw error;
      this.logger.error(
        `Failed to approve KYC for user ${command.userId}: ${error instanceof Error ? error.message : String(error)}`,
        error instanceof Error ? error.stack : undefined,
        'ApproveKycHandler',
      );
      throw new InternalServerErrorException('Lỗi khi duyệt KYC');
    }
  }
}
