import type { EventBus } from '@nestjs/cqrs';
import type { ILeadRepository } from '../../domain/repositories/lead.repository';
import { CreateLeadCommand } from '../commands/create-lead/create-lead.command';
import { CreateLeadHandler } from '../commands/create-lead/create-lead.handler';

describe('CreateLeadHandler', () => {
  let handler: CreateLeadHandler;
  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 CreateLeadHandler(
      mockLeadRepo as any,
      mockEventBus as unknown as EventBus,
      mockPrisma as any,
      mockLogger as any,
    );
  });

  it('creates a lead successfully', async () => {
    mockPrisma.agent.findUnique.mockResolvedValue({ id: 'agent-1', userId: 'user-1' });
    mockLeadRepo.save.mockResolvedValue(undefined);

    const command = new CreateLeadCommand(
      'user-1',
      'Nguyễn Văn A',
      '0901234567',
      'a@example.com',
      'WEBSITE',
      75,
      { note: 'Interested in District 7' },
    );

    const result = await handler.execute(command);

    expect(result.id).toBeDefined();
    expect(result.status).toBe('NEW');
    expect(result.createdAt).toBeDefined();
    expect(mockLeadRepo.save).toHaveBeenCalledTimes(1);
    expect(mockEventBus.publish).toHaveBeenCalled();
  });

  it('creates a lead with null score', async () => {
    mockPrisma.agent.findUnique.mockResolvedValue({ id: 'agent-1', userId: 'user-1' });
    mockLeadRepo.save.mockResolvedValue(undefined);

    const command = new CreateLeadCommand(
      'user-1',
      'Nguyễn Văn B',
      '0907654321',
      null,
      'REFERRAL',
      null,
      null,
    );

    const result = await handler.execute(command);

    expect(result.id).toBeDefined();
    expect(result.status).toBe('NEW');
  });

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

    const command = new CreateLeadCommand(
      'not-an-agent',
      'Nguyễn Văn A',
      '0901234567',
      null,
      'WEBSITE',
      null,
      null,
    );

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

  it('throws ValidationException for invalid score', async () => {
    mockPrisma.agent.findUnique.mockResolvedValue({ id: 'agent-1', userId: 'user-1' });

    const command = new CreateLeadCommand(
      'user-1',
      'Nguyễn Văn A',
      '0901234567',
      null,
      'WEBSITE',
      150,
      null,
    );

    await expect(handler.execute(command)).rejects.toThrow(
      'Điểm lead phải từ 0 đến 100',
    );
    expect(mockLeadRepo.save).not.toHaveBeenCalled();
  });
});
