import { ReviewDeletedListener } from '../listeners/review-deleted.listener';

describe('ReviewDeletedListener', () => {
  let listener: ReviewDeletedListener;
  let mockPrisma: {
    review: { aggregate: ReturnType<typeof vi.fn> };
    agent: { update: ReturnType<typeof vi.fn> };
  };
  let mockLogger: { log: ReturnType<typeof vi.fn>; warn: ReturnType<typeof vi.fn> };

  beforeEach(() => {
    mockPrisma = {
      review: { aggregate: vi.fn() },
      agent: { update: vi.fn().mockResolvedValue(undefined) },
    };
    mockLogger = { log: vi.fn(), warn: vi.fn() };

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

  it('recalculates agent quality score on review deletion', async () => {
    mockPrisma.review.aggregate.mockResolvedValue({
      _avg: { rating: 4.2 },
      _count: { rating: 5 },
    });

    await listener.handle({
      aggregateId: 'review-1',
      userId: 'user-1',
      targetType: 'AGENT',
      targetId: 'agent-1',
      eventName: 'review.deleted',
      occurredAt: new Date(),
    });

    expect(mockPrisma.agent.update).toHaveBeenCalledWith({
      where: { id: 'agent-1' },
      data: { qualityScore: 4.2 },
    });
  });

  it('handles zero reviews after deletion', async () => {
    mockPrisma.review.aggregate.mockResolvedValue({
      _avg: { rating: null },
      _count: { rating: 0 },
    });

    await listener.handle({
      aggregateId: 'review-3',
      userId: 'user-3',
      targetType: 'AGENT',
      targetId: 'agent-2',
      eventName: 'review.deleted',
      occurredAt: new Date(),
    });

    expect(mockPrisma.agent.update).toHaveBeenCalledWith({
      where: { id: 'agent-2' },
      data: { qualityScore: 0 },
    });
  });
});
