import { AgentVerifiedEvent } from '@modules/auth/domain/events/agent-verified.event';
import { SendNotificationCommand } from '../commands/send-notification/send-notification.command';
import { AgentVerifiedListener } from '../listeners/agent-verified.listener';

describe('AgentVerifiedListener', () => {
  let listener: AgentVerifiedListener;
  let mockCommandBus: { execute: ReturnType<typeof vi.fn> };
  let mockPrisma: { agent: { findUnique: ReturnType<typeof vi.fn> } };
  let mockLogger: { log: ReturnType<typeof vi.fn>; warn: ReturnType<typeof vi.fn>; error: ReturnType<typeof vi.fn> };

  beforeEach(() => {
    mockCommandBus = { execute: vi.fn().mockResolvedValue(undefined) };
    mockPrisma = {
      agent: {
        findUnique: vi.fn(),
      },
    };
    mockLogger = { log: vi.fn(), warn: vi.fn(), error: vi.fn() };

    listener = new AgentVerifiedListener(
      mockCommandBus as any,
      mockPrisma as any,
      mockLogger as any,
    );
  });

  it('sends email notification when agent has email', async () => {
    mockPrisma.agent.findUnique.mockResolvedValue({
      id: 'agent-1',
      user: { id: 'user-1', email: 'agent@test.com' },
    });

    const event = new AgentVerifiedEvent('agent-1', 'user-1');
    await listener.handle(event);

    expect(mockCommandBus.execute).toHaveBeenCalledWith(
      expect.any(SendNotificationCommand),
    );

    const cmd = mockCommandBus.execute.mock.calls[0]![0] as SendNotificationCommand;
    expect(cmd.userId).toBe('user-1');
    expect(cmd.channel).toBe('EMAIL');
    expect(cmd.templateKey).toBe('agent.verified');
    expect(cmd.recipientAddress).toBe('agent@test.com');
  });

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

    const event = new AgentVerifiedEvent('agent-1', 'user-1');
    await listener.handle(event);

    expect(mockCommandBus.execute).not.toHaveBeenCalled();
  });

  it('skips notification when agent has no email', async () => {
    mockPrisma.agent.findUnique.mockResolvedValue({
      id: 'agent-1',
      user: { id: 'user-1', email: null },
    });

    const event = new AgentVerifiedEvent('agent-1', 'user-1');
    await listener.handle(event);

    expect(mockCommandBus.execute).not.toHaveBeenCalled();
  });
});
