import { describe, it, expect, vi, beforeEach } from 'vitest';
import { PricesService } from '../../../src/modules/prices/prices.service.js';
import { NotFoundError } from '../../../src/common/errors.js';

describe('PricesService', () => {
  let service: PricesService;

  const mockPricesRepo = {
    create: vi.fn(),
    createMany: vi.fn(),
    findByProduct: vi.fn(),
    compareStores: vi.fn(),
    getAnalytics: vi.fn(),
    getLatestForProduct: vi.fn(),
  };

  const mockProductsRepo = {
    findById: vi.fn(),
    findByIds: vi.fn(),
  };

  const mockStoresRepo = {
    findById: vi.fn(),
  };

  beforeEach(() => {
    vi.clearAllMocks();
    service = new PricesService({
      pricesRepository: mockPricesRepo as any,
      productsRepository: mockProductsRepo as any,
      storesRepository: mockStoresRepo as any,
    });
  });

  describe('recordPrice', () => {
    it('calculates unit price and persists data on existing linkages', async () => {
      mockProductsRepo.findById.mockResolvedValue({ name: 'Milk' });
      mockStoresRepo.findById.mockResolvedValue({ name: 'Target' });
      mockPricesRepo.create.mockResolvedValue({ _id: 'rec1' });

      const result = await service.recordPrice(
        { productId: 'p1', storeId: 's1', price: 4, quantity: 2, unit: 'ml' as any, currency: 'USD' },
        'hh1',
        'u1'
      );

      expect(mockPricesRepo.create).toHaveBeenCalledWith(
        expect.objectContaining({
          productName: 'Milk',
          storeName: 'Target',
          pricePerUnit: 2,
        })
      );
      expect(result._id).toBe('rec1');
    });

    it('handles zero quantity and defaults date to current when recording price', async () => {
      mockProductsRepo.findById.mockResolvedValue({ name: 'Bread' });
      mockStoresRepo.findById.mockResolvedValue({ name: 'Aldi' });
      mockPricesRepo.create.mockImplementation(arg => Promise.resolve({ ...arg, _id: 'rec1' }));

      const result = await service.recordPrice(
        { productId: 'p2', storeId: 's2', price: 5, quantity: 0, unit: 'g' as any, currency: 'USD' },
        'hh1',
        'u1'
      );

      expect(mockPricesRepo.create).toHaveBeenCalledWith(
        expect.objectContaining({
          pricePerUnit: 5,
          date: expect.any(Date),
        })
      );
      expect(result._id).toBe('rec1');
    });

    it('throws NotFound if product is invalid', async () => {
      mockProductsRepo.findById.mockResolvedValue(null);
      await expect(
        service.recordPrice(
          { productId: 'p1', storeId: 's1', price: 1, quantity: 1, unit: 'g' as any, currency: 'USD' },
          'hh1',
          'u1'
        )
      ).rejects.toThrow(NotFoundError);
    });
  });

  describe('recordBulkPrices', () => {
    it('ingests multiple mappings throwing notFound if one catalog match fails', async () => {
      mockStoresRepo.findById.mockResolvedValue({ name: 'Aldi' });
      mockProductsRepo.findByIds.mockResolvedValue([{ _id: 'p1', name: 'Bread' }]);
      mockPricesRepo.createMany.mockImplementation(args => args);

      const result = await service.recordBulkPrices(
        {
          storeId: 's1',
          items: [{ productId: 'p1', price: 3, quantity: 1, unit: 'g' as any }],
        },
        'hh1',
        'u1'
      );

      expect(mockPricesRepo.createMany).toHaveBeenCalled();
      expect(result).toHaveLength(1);
      expect(result[0].productName).toBe('Bread');
    });

    it('throws NotFoundError if a product is missing from the catalog', async () => {
      mockStoresRepo.findById.mockResolvedValue({ name: 'Aldi' });
      mockProductsRepo.findByIds.mockResolvedValue([]); // Missing product
      await expect(
        service.recordBulkPrices(
          { storeId: 's1', items: [{ productId: 'p1', price: 3, quantity: 1, unit: 'g' as any }] },
          'hh1',
          'u1'
        )
      ).rejects.toThrow(NotFoundError);
    });

    it('throws NotFoundError if store is missing', async () => {
      mockStoresRepo.findById.mockResolvedValue(null);
      await expect(
        service.recordBulkPrices(
          { storeId: 's1', items: [{ productId: 'p1', price: 3, quantity: 1, unit: 'g' as any }] },
          'hh1',
          'u1'
        )
      ).rejects.toThrow(NotFoundError);
    });
  });

  describe('Wrappers (getPriceHistory, compareStores, getAnalytics)', () => {
    it('delegates to repository correctly', async () => {
      mockPricesRepo.findByProduct.mockResolvedValue('history');
      mockPricesRepo.compareStores.mockResolvedValue('compare');
      mockPricesRepo.getAnalytics.mockResolvedValue('analytics');

      expect(await service.getPriceHistory('p1', 'hh1', { page: 1, limit: 10 })).toBe('history');
      expect(await service.compareStores('p1', 'hh1')).toBe('compare');
      expect(await service.getAnalytics('hh1')).toBe('analytics');
    });
  });

  describe('estimatePrice', () => {
    it('returns price from specific store if present', async () => {
      mockPricesRepo.getLatestForProduct.mockResolvedValue({ price: 8 });
      const val = await service.estimatePrice('prod1', 'hh1', 'storeA');
      expect(val).toBe(8);
    });

    it('falls back to generic if requested store history is missing', async () => {
      // First call (restricted to storeId): empty
      mockPricesRepo.getLatestForProduct.mockResolvedValueOnce(null);
      // Second call (generic): matches
      mockPricesRepo.getLatestForProduct.mockResolvedValueOnce({ price: 12 });

      const val = await service.estimatePrice('prod1', 'hh1', 'storeA');
      expect(mockPricesRepo.getLatestForProduct).toHaveBeenCalledTimes(2);
      expect(val).toBe(12);
    });

    it('returns null if generic lookup also fails', async () => {
      mockPricesRepo.getLatestForProduct.mockResolvedValue(null);
      const val = await service.estimatePrice('prod1', 'hh1', 'storeA');
      expect(val).toBeNull();
    });

    it('returns null if no storeId provided and generic lookup fails', async () => {
      mockPricesRepo.getLatestForProduct.mockResolvedValue(null);
      const val = await service.estimatePrice('prod1', 'hh1');
      expect(val).toBeNull();
    });
  });
});
