import type { IAgentRepository, AgentDashboardData } from '../../domain/repositories/agent.repository';
import { GetAgentDashboardHandler } from '../queries/get-agent-dashboard/get-agent-dashboard.handler';
import { GetAgentDashboardQuery } from '../queries/get-agent-dashboard/get-agent-dashboard.query';

describe('GetAgentDashboardHandler', () => {
  let handler: GetAgentDashboardHandler;
  let mockAgentRepo: { [K in keyof IAgentRepository]: ReturnType<typeof vi.fn> };

  beforeEach(() => {
    mockAgentRepo = {
      findByUserId: vi.fn(),
      findById: vi.fn(),
      updateQualityScore: vi.fn(),
      getDashboard: vi.fn(),
    };

    handler = new GetAgentDashboardHandler(mockAgentRepo as any);
  });

  it('returns dashboard data', async () => {
    mockAgentRepo.findByUserId.mockResolvedValue({
      id: 'agent-1',
      userId: 'user-1',
      qualityScore: 85,
    });

    const mockDashboard: AgentDashboardData = {
      agentId: 'agent-1',
      qualityScore: 85,
      totalDeals: 12,
      responseTimeAvg: 600,
      isVerified: true,
      totalLeads: 30,
      leadsByStatus: { NEW: 5, CONTACTED: 10, QUALIFIED: 5, NEGOTIATING: 3, CONVERTED: 5, LOST: 2 },
      conversionRate: 0.167,
      totalInquiries: 45,
      unreadInquiries: 3,
      totalListings: 15,
      activeListings: 10,
      avgReviewRating: 4.5,
      totalReviews: 20,
    };
    mockAgentRepo.getDashboard.mockResolvedValue(mockDashboard);

    const query = new GetAgentDashboardQuery('user-1');
    const result = await handler.execute(query);

    expect(result).toEqual(mockDashboard);
    expect(result.agentId).toBe('agent-1');
    expect(result.qualityScore).toBe(85);
    expect(mockAgentRepo.findByUserId).toHaveBeenCalledWith('user-1');
    expect(mockAgentRepo.getDashboard).toHaveBeenCalledWith('agent-1');
  });

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

    const query = new GetAgentDashboardQuery('not-an-agent');

    await expect(handler.execute(query)).rejects.toThrow(
      'Không tìm thấy thông tin môi giới',
    );
    expect(mockAgentRepo.getDashboard).not.toHaveBeenCalled();
  });
});
