import type { EventBus } from '@nestjs/cqrs';
import type { IInquiryRepository } from '../../domain/repositories/inquiry.repository';
import { CreateInquiryCommand } from '../commands/create-inquiry/create-inquiry.command';
import { CreateInquiryHandler } from '../commands/create-inquiry/create-inquiry.handler';

describe('CreateInquiryHandler', () => {
  let handler: CreateInquiryHandler;
  let mockInquiryRepo: { [K in keyof IInquiryRepository]: ReturnType<typeof vi.fn> };
  let mockEventBus: { publish: ReturnType<typeof vi.fn> };
  let mockPrisma: {
    listing: { findUnique: ReturnType<typeof vi.fn> };
  };

  beforeEach(() => {
    mockInquiryRepo = {
      findById: vi.fn(),
      save: vi.fn(),
      markAsRead: vi.fn(),
      findByListing: vi.fn(),
      findByAgent: vi.fn(),
      countUnreadByAgent: vi.fn(),
    };

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

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

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

    handler = new CreateInquiryHandler(
      mockInquiryRepo as any,
      mockEventBus as unknown as EventBus,
      mockPrisma as any,
      mockLogger as any,
    );
  });

  it('creates an inquiry successfully', async () => {
    mockPrisma.listing.findUnique.mockResolvedValue({ id: 'listing-1' });
    mockInquiryRepo.save.mockResolvedValue(undefined);

    const command = new CreateInquiryCommand(
      'user-1',
      'listing-1',
      'Tôi muốn xem nhà',
      '0901234567',
    );

    const result = await handler.execute(command);

    expect(result.id).toBeDefined();
    expect(result.listingId).toBe('listing-1');
    expect(result.createdAt).toBeDefined();
    expect(mockInquiryRepo.save).toHaveBeenCalledTimes(1);
    expect(mockEventBus.publish).toHaveBeenCalled();
  });

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

    const command = new CreateInquiryCommand(
      'user-1',
      'listing-not-exist',
      'Tôi muốn xem nhà',
      null,
    );

    await expect(handler.execute(command)).rejects.toThrow(
      "Listing with id 'listing-not-exist' not found",
    );
    expect(mockInquiryRepo.save).not.toHaveBeenCalled();
  });

  it('publishes domain events after saving', async () => {
    mockPrisma.listing.findUnique.mockResolvedValue({ id: 'listing-1' });
    mockInquiryRepo.save.mockResolvedValue(undefined);

    const command = new CreateInquiryCommand(
      'user-1',
      'listing-1',
      'Cho tôi hỏi giá',
      null,
    );

    await handler.execute(command);

    expect(mockEventBus.publish).toHaveBeenCalledTimes(1);
    expect(mockEventBus.publish).toHaveBeenCalledWith(
      expect.objectContaining({
        eventName: 'inquiry.created',
        listingId: 'listing-1',
        userId: 'user-1',
      }),
    );
  });
});
