import type { EventBus } from '@nestjs/cqrs';
import { LeadEntity } from '../../domain/entities/lead.entity';
import type { ILeadRepository } from '../../domain/repositories/lead.repository';
import { DeleteLeadCommand } from '../commands/delete-lead/delete-lead.command';
import { DeleteLeadHandler } from '../commands/delete-lead/delete-lead.handler';

describe('DeleteLeadHandler', () => {
  let handler: DeleteLeadHandler;
  let mockLeadRepo: { [K in keyof ILeadRepository]: ReturnType<typeof vi.fn> };
  let mockEventBus: { publish: ReturnType<typeof vi.fn> };
  let mockPrisma: {
    agent: { findUnique: ReturnType<typeof vi.fn> };
  };

  beforeEach(() => {
    mockLeadRepo = {
      findById: vi.fn(),
      save: vi.fn(),
      update: vi.fn(),
      delete: vi.fn(),
      findByAgent: vi.fn(),
      getStatsByAgent: vi.fn(),
    };

    mockEventBus = { publish: vi.fn() };

    mockPrisma = {
      agent: { findUnique: vi.fn() },
    };

    const mockLogger = { log: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn(), verbose: vi.fn() };

    handler = new DeleteLeadHandler(
      mockLeadRepo as any,
      mockEventBus as unknown as EventBus,
      mockPrisma as any,
      mockLogger as any,
    );
  });

  it('deletes a lead successfully', async () => {
    mockPrisma.agent.findUnique.mockResolvedValue({ id: 'agent-1' });

    const lead = new LeadEntity('lead-1', {
      agentId: 'agent-1',
      name: 'Nguyễn Văn A',
      phone: '0901234567',
      email: null,
      source: 'WEBSITE',
      score: null,
      notes: null,
      status: 'NEW',
    });
    mockLeadRepo.findById.mockResolvedValue(lead);
    mockLeadRepo.delete.mockResolvedValue(undefined);

    const command = new DeleteLeadCommand('lead-1', 'user-1');

    await handler.execute(command);

    expect(mockLeadRepo.delete).toHaveBeenCalledWith('lead-1');
  });

  it('throws NotFoundException when agent not found', async () => {
    mockPrisma.agent.findUnique.mockResolvedValue(null);

    const command = new DeleteLeadCommand('lead-1', 'not-an-agent');

    await expect(handler.execute(command)).rejects.toThrow(
      "Agent with id 'not-an-agent' not found",
    );
  });

  it('throws NotFoundException when lead not found', async () => {
    mockPrisma.agent.findUnique.mockResolvedValue({ id: 'agent-1' });
    mockLeadRepo.findById.mockResolvedValue(null);

    const command = new DeleteLeadCommand('lead-not-exist', 'user-1');

    await expect(handler.execute(command)).rejects.toThrow(
      "Lead with id 'lead-not-exist' not found",
    );
  });

  it('throws ForbiddenException when agent does not own the lead', async () => {
    mockPrisma.agent.findUnique.mockResolvedValue({ id: 'agent-2' });

    const lead = new LeadEntity('lead-1', {
      agentId: 'agent-1',
      name: 'Nguyễn Văn A',
      phone: '0901234567',
      email: null,
      source: 'WEBSITE',
      score: null,
      notes: null,
      status: 'NEW',
    });
    mockLeadRepo.findById.mockResolvedValue(lead);

    const command = new DeleteLeadCommand('lead-1', 'user-2');

    await expect(handler.execute(command)).rejects.toThrow(
      'Bạn chỉ có thể xóa lead của chính mình',
    );
    expect(mockLeadRepo.delete).not.toHaveBeenCalled();
  });
});
