import { Inject } from '@nestjs/common';
import { CommandHandler, type EventBus, type ICommandHandler } from '@nestjs/cqrs';
import { USER_REPOSITORY, type IUserRepository } from '@modules/auth/domain/repositories/user.repository';
import { NotFoundException, ValidationException } 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,
  ) {}

  async execute(command: ApproveKycCommand): Promise<ApproveKycResult> {
    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',
    };
  }
}
