import { Inject, InternalServerErrorException } from '@nestjs/common';
import { CommandHandler, EventBus, type ICommandHandler } from '@nestjs/cqrs';
import { DomainException, ForbiddenException, NotFoundException, PrismaService, LoggerService } from '@modules/shared';
import { LEAD_REPOSITORY, type ILeadRepository } from '../../../domain/repositories/lead.repository';
import { DeleteLeadCommand } from './delete-lead.command';

@CommandHandler(DeleteLeadCommand)
export class DeleteLeadHandler implements ICommandHandler<DeleteLeadCommand> {
  constructor(
    @Inject(LEAD_REPOSITORY) private readonly leadRepo: ILeadRepository,
    private readonly eventBus: EventBus,
    private readonly prisma: PrismaService,
    private readonly logger: LoggerService,
  ) {}

  async execute(command: DeleteLeadCommand): Promise<void> {
    try {
      // Look up agent by userId
      const agent = await this.prisma.agent.findUnique({
        where: { userId: command.agentUserId },
      });
      if (!agent) {
        throw new NotFoundException('Agent', command.agentUserId);
      }

      const lead = await this.leadRepo.findById(command.leadId);
      if (!lead) {
        throw new NotFoundException('Lead', command.leadId);
      }

      // Verify agent ownership
      if (lead.agentId !== agent.id) {
        throw new ForbiddenException('Bạn chỉ có thể xóa lead của chính mình');
      }

      await this.leadRepo.delete(command.leadId);

      this.logger.log(`Lead ${command.leadId} deleted by agent ${agent.id}`, 'DeleteLeadHandler');
    } catch (error) {
      if (error instanceof DomainException) throw error;
      this.logger.error(
        `Failed to delete lead: ${error instanceof Error ? error.message : String(error)}`,
        error instanceof Error ? error.stack : undefined,
        'DeleteLeadHandler',
      );
      throw new InternalServerErrorException('Lỗi khi xóa lead');
    }
  }
}
