import { describe, it, expect, vi, beforeEach } from 'vitest';

const { mockGet, mockPost } = vi.hoisted(() => ({
  mockGet: vi.fn(),
  mockPost: vi.fn(),
}));

vi.mock('../../src/services/api-client', () => ({
  apiClient: { get: mockGet, post: mockPost },
}));

import { recordPrice, getPriceHistory, compareStores, getPriceAnalytics } from '../../src/services/medicine-prices';

beforeEach(() => vi.clearAllMocks());

describe('medicine-prices service', () => {
  it('recordPrice calls POST', async () => {
    mockPost.mockResolvedValue({ _id: 'pr-1' });
    const data = { medicineProductId: 'mp-1', storeId: 'st-1', price: 10 } as never;
    await recordPrice('hh1', data);
    expect(mockPost).toHaveBeenCalledWith('/households/hh1/medicine-prices', data);
  });

  it('getPriceHistory with no query', async () => {
    mockGet.mockResolvedValue({ data: [] });
    await getPriceHistory('hh1', 'med-1');
    expect(mockGet).toHaveBeenCalledWith('/households/hh1/medicine-prices/history/med-1');
  });

  it('getPriceHistory builds query string', async () => {
    mockGet.mockResolvedValue({ data: [] });
    await getPriceHistory('hh1', 'med-1', { storeId: 'st-1', startDate: '2026-01-01' });
    expect(mockGet).toHaveBeenCalledWith(expect.stringContaining('storeId=st-1'));
    expect(mockGet).toHaveBeenCalledWith(expect.stringContaining('startDate=2026-01-01'));
  });

  it('getPriceHistory with endDate, cursor and limit', async () => {
    mockGet.mockResolvedValue({ data: [] });
    await getPriceHistory('hh1', 'med-1', { endDate: '2026-12-31', cursor: 'cur1', limit: 10 });
    expect(mockGet).toHaveBeenCalledWith(expect.stringContaining('endDate=2026-12-31'));
    expect(mockGet).toHaveBeenCalledWith(expect.stringContaining('cursor=cur1'));
    expect(mockGet).toHaveBeenCalledWith(expect.stringContaining('limit=10'));
  });

  it('compareStores calls GET with medicineId', async () => {
    mockGet.mockResolvedValue({ data: [] });
    await compareStores('hh1', 'med-1');
    expect(mockGet).toHaveBeenCalledWith('/households/hh1/medicine-prices/compare/med-1');
  });

  it('getPriceAnalytics uses default period', async () => {
    mockGet.mockResolvedValue({});
    await getPriceAnalytics('hh1');
    expect(mockGet).toHaveBeenCalledWith('/households/hh1/medicine-prices/analytics?period=month');
  });

  it('getPriceAnalytics uses custom period', async () => {
    mockGet.mockResolvedValue({});
    await getPriceAnalytics('hh1', 'year');
    expect(mockGet).toHaveBeenCalledWith('/households/hh1/medicine-prices/analytics?period=year');
  });
});
