import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import {
  fetchHistoryPage,
  getNextPageParam,
  HISTORY_PAGE_SIZE,
  type HistoryResponse
} from './history';

vi.mock('./client', () => ({
  api: {
    get: vi.fn()
  }
}));

import { api } from './client';

describe('history API helpers', () => {
  beforeEach(() => {
    vi.mocked(api.get).mockReset();
  });

  afterEach(() => {
    vi.restoreAllMocks();
  });

  it('HISTORY_PAGE_SIZE is 50', () => {
    expect(HISTORY_PAGE_SIZE).toBe(50);
  });

  it('fetchHistoryPage hits /api/me/history?offset=N&limit=50', async () => {
    vi.mocked(api.get).mockResolvedValue({ events: [], has_more: false });
    await fetchHistoryPage(50);
    expect(api.get).toHaveBeenCalledWith('/api/me/history?offset=50&limit=50');
  });

  it('fetchHistoryPage uses offset=0 by default', async () => {
    vi.mocked(api.get).mockResolvedValue({ events: [], has_more: false });
    await fetchHistoryPage();
    expect(api.get).toHaveBeenCalledWith('/api/me/history?offset=0&limit=50');
  });

  it('getNextPageParam returns next offset when has_more is true', () => {
    const page: HistoryResponse = { events: [], has_more: true };
    expect(getNextPageParam(page, [], 0)).toBe(50);
    expect(getNextPageParam(page, [], 50)).toBe(100);
  });

  it('getNextPageParam returns undefined when has_more is false', () => {
    const page: HistoryResponse = { events: [], has_more: false };
    expect(getNextPageParam(page, [], 50)).toBeUndefined();
  });
});
