import type { IInquiryRepository } from '../../domain/repositories/inquiry.repository';
import { GetInquiriesByAgentHandler } from '../queries/get-inquiries-by-agent/get-inquiries-by-agent.handler';
import { GetInquiriesByAgentQuery } from '../queries/get-inquiries-by-agent/get-inquiries-by-agent.query';

describe('GetInquiriesByAgentHandler', () => {
  let handler: GetInquiriesByAgentHandler;
  let mockInquiryRepo: { [K in keyof IInquiryRepository]: ReturnType<typeof vi.fn> };
  let mockPrisma: {
    agent: { 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(),
    };

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

    handler = new GetInquiriesByAgentHandler(
      mockInquiryRepo as any,
      mockPrisma as any,
    );
  });

  it('returns paginated results', async () => {
    mockPrisma.agent.findUnique.mockResolvedValue({ id: 'agent-1' });

    const mockResult = {
      data: [
        {
          id: 'inq-1',
          listingId: 'listing-1',
          userId: 'user-1',
          message: 'Tôi muốn xem nhà',
          phone: '0901234567',
          isRead: false,
          createdAt: new Date(),
        },
      ],
      total: 1,
      page: 1,
      limit: 20,
      totalPages: 1,
    };
    mockInquiryRepo.findByAgent.mockResolvedValue(mockResult);

    const query = new GetInquiriesByAgentQuery('agent-user-1', 1, 20);
    const result = await handler.execute(query);

    expect(result).toEqual(mockResult);
    expect(result.data).toHaveLength(1);
    expect(mockPrisma.agent.findUnique).toHaveBeenCalledWith({
      where: { userId: 'agent-user-1' },
      select: { id: true },
    });
    expect(mockInquiryRepo.findByAgent).toHaveBeenCalledWith('agent-1', 1, 20);
  });

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

    const query = new GetInquiriesByAgentQuery('not-an-agent', 1, 20);

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