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

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

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

import { listCabinetEvents, getEventsByItem, getSpendingSummary } from '../../src/services/cabinet-events';

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

describe('cabinet-events service', () => {
  it('listCabinetEvents with no query', async () => {
    mockGet.mockResolvedValue({ data: [] });
    await listCabinetEvents('hh1');
    expect(mockGet).toHaveBeenCalledWith('/households/hh1/cabinet-events');
  });

  it('listCabinetEvents builds query string', async () => {
    mockGet.mockResolvedValue({ data: [] });
    await listCabinetEvents('hh1', {
      medicineId: 'med-1',
      eventType: 'dispense',
      startDate: '2026-01-01',
      endDate: '2026-02-01',
    });
    expect(mockGet).toHaveBeenCalledWith(expect.stringContaining('medicineId=med-1'));
    expect(mockGet).toHaveBeenCalledWith(expect.stringContaining('eventType=dispense'));
    expect(mockGet).toHaveBeenCalledWith(expect.stringContaining('startDate=2026-01-01'));
  });

  it('getEventsByItem builds URL with cabinetItemId', async () => {
    mockGet.mockResolvedValue({ data: [] });
    await getEventsByItem('hh1', 'ci-1', { limit: 5 });
    expect(mockGet).toHaveBeenCalledWith(expect.stringContaining('/cabinet-events/by-item/ci-1'));
    expect(mockGet).toHaveBeenCalledWith(expect.stringContaining('limit=5'));
  });

  it('listCabinetEvents with cursor and limit', async () => {
    mockGet.mockResolvedValue({ data: [] });
    await listCabinetEvents('hh1', { cursor: 'cur1', limit: 10 });
    expect(mockGet).toHaveBeenCalledWith(expect.stringContaining('cursor=cur1'));
    expect(mockGet).toHaveBeenCalledWith(expect.stringContaining('limit=10'));
  });

  it('getEventsByItem with cursor', async () => {
    mockGet.mockResolvedValue({ data: [] });
    await getEventsByItem('hh1', 'ci-1', { cursor: 'cur2' });
    expect(mockGet).toHaveBeenCalledWith(expect.stringContaining('cursor=cur2'));
  });

  it('getSpendingSummary with no query', async () => {
    mockGet.mockResolvedValue({});
    await getSpendingSummary('hh1');
    expect(mockGet).toHaveBeenCalledWith('/households/hh1/cabinet-events/spending-summary');
  });

  it('getSpendingSummary builds query string', async () => {
    mockGet.mockResolvedValue({});
    await getSpendingSummary('hh1', { period: 'month', medicineId: 'med-1' });
    expect(mockGet).toHaveBeenCalledWith(expect.stringContaining('period=month'));
    expect(mockGet).toHaveBeenCalledWith(expect.stringContaining('medicineId=med-1'));
  });
});
