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

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

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

import {
  listPurchases,
  getPurchase,
  createPurchase,
  updatePurchase,
  receivePurchase,
  deletePurchase,
} from '../../src/services/purchases';

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

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

  it('listPurchases builds query string', async () => {
    mockGet.mockResolvedValue({ data: [] });
    await listPurchases('hh1', { status: 'ordered', storeId: 'st-1', limit: 10 });
    expect(mockGet).toHaveBeenCalledWith(expect.stringContaining('status=ordered'));
    expect(mockGet).toHaveBeenCalledWith(expect.stringContaining('storeId=st-1'));
  });

  it('getPurchase calls GET', async () => {
    mockGet.mockResolvedValue({ _id: 'p-1' });
    await getPurchase('hh1', 'p-1');
    expect(mockGet).toHaveBeenCalledWith('/households/hh1/purchases/p-1');
  });

  it('createPurchase calls POST', async () => {
    mockPost.mockResolvedValue({ _id: 'p-1' });
    const data = { storeId: 'st-1', items: [] } as never;
    await createPurchase('hh1', data);
    expect(mockPost).toHaveBeenCalledWith('/households/hh1/purchases', data);
  });

  it('updatePurchase calls PATCH', async () => {
    mockPatch.mockResolvedValue({ _id: 'p-1' });
    await updatePurchase('hh1', 'p-1', { notes: 'updated' } as never);
    expect(mockPatch).toHaveBeenCalledWith('/households/hh1/purchases/p-1', { notes: 'updated' });
  });

  it('receivePurchase calls POST with empty body', async () => {
    mockPost.mockResolvedValue({ addedCount: 1, priceRecordsCreated: 0 });
    await receivePurchase('hh1', 'p-1');
    expect(mockPost).toHaveBeenCalledWith('/households/hh1/purchases/p-1/receive', {});
  });

  it('deletePurchase calls DELETE', async () => {
    mockDelete.mockResolvedValue({ _id: 'p-1' });
    await deletePurchase('hh1', 'p-1');
    expect(mockDelete).toHaveBeenCalledWith('/households/hh1/purchases/p-1');
  });
});
