import { describe, it, expect, vi, beforeEach } from 'vitest';
import { GetPriceHistoryHandler } from '../queries/get-price-history/get-price-history.handler';
import { GetPriceHistoryQuery } from '../queries/get-price-history/get-price-history.query';

describe('GetPriceHistoryHandler', () => {
  let handler: GetPriceHistoryHandler;
  let mockPrisma: { priceHistory: { findMany: ReturnType<typeof vi.fn> } };

  beforeEach(() => {
    mockPrisma = {
      priceHistory: { findMany: vi.fn() },
    };
    handler = new GetPriceHistoryHandler(mockPrisma as any);
  });

  it('should query price history for the given listing ordered by changedAt desc', async () => {
    const mockHistory = [
      { id: 'ph-2', oldPrice: 5_000_000_000n, newPrice: 6_000_000_000n, source: 'manual_update', changedAt: new Date('2026-04-16') },
      { id: 'ph-1', oldPrice: 4_000_000_000n, newPrice: 5_000_000_000n, source: 'manual_update', changedAt: new Date('2026-04-10') },
    ];
    mockPrisma.priceHistory.findMany.mockResolvedValue(mockHistory);

    const query = new GetPriceHistoryQuery('listing-1');
    const result = await handler.execute(query);

    expect(result).toEqual(mockHistory);
    expect(mockPrisma.priceHistory.findMany).toHaveBeenCalledWith({
      where: { listingId: 'listing-1' },
      orderBy: { changedAt: 'desc' },
      select: {
        id: true,
        oldPrice: true,
        newPrice: true,
        source: true,
        changedAt: true,
      },
    });
  });

  it('should return empty array when no history exists', async () => {
    mockPrisma.priceHistory.findMany.mockResolvedValue([]);

    const query = new GetPriceHistoryQuery('listing-no-history');
    const result = await handler.execute(query);

    expect(result).toEqual([]);
  });

  it('should include source field in the select', async () => {
    mockPrisma.priceHistory.findMany.mockResolvedValue([
      { id: 'ph-1', oldPrice: 1n, newPrice: 2n, source: 'admin_override', changedAt: new Date() },
    ]);

    const result = await handler.execute(new GetPriceHistoryQuery('listing-1'));

    expect(result[0].source).toBe('admin_override');
  });
});
