import { ListingApprovedEvent } from '@modules/admin/domain/events/listing-approved.event';
import { SendNotificationCommand } from '../commands/send-notification/send-notification.command';
import { ListingApprovedListener } from '../listeners/listing-approved.listener';

describe('ListingApprovedListener', () => {
  let listener: ListingApprovedListener;
  let mockCommandBus: { execute: ReturnType<typeof vi.fn> };
  let mockPrisma: { listing: { 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 = {
      listing: { findUnique: vi.fn() },
    };
    mockLogger = { log: vi.fn(), warn: vi.fn(), error: vi.fn() };

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

  it('sends email notification when listing is approved', async () => {
    mockPrisma.listing.findUnique.mockResolvedValue({
      property: { title: 'Căn hộ 2PN Quận 7' },
      seller: { id: 'seller-1', email: 'seller@test.com' },
    });

    const event = new ListingApprovedEvent('listing-1', 'admin-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('seller-1');
    expect(cmd.channel).toBe('EMAIL');
    expect(cmd.templateKey).toBe('listing.approved');
    expect(cmd.templateData).toEqual({ listingTitle: 'Căn hộ 2PN Quận 7' });
    expect(cmd.recipientAddress).toBe('seller@test.com');
  });

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

    const event = new ListingApprovedEvent('listing-1', 'admin-1');
    await listener.handle(event);

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

  it('skips notification when seller has no email', async () => {
    mockPrisma.listing.findUnique.mockResolvedValue({
      property: { title: 'Căn hộ 2PN Quận 7' },
      seller: { id: 'seller-1', email: null },
    });

    const event = new ListingApprovedEvent('listing-1', 'admin-1');
    await listener.handle(event);

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