import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { AlqoveClient } from '../client';

/**
 * The API is Laravel, which only parses repeated query params into an array
 * when the key carries `[]`. Getting this wrong is silent: the backend's
 * `array` validation rejects the request and the caller sees an empty grid.
 */
describe('query parameter encoding', () => {
  let fetchMock: ReturnType<typeof vi.fn>;

  beforeEach(() => {
    fetchMock = vi.fn().mockResolvedValue({ ok: true, json: async () => ({ data: [] }) });
    vi.stubGlobal('fetch', fetchMock);
  });

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

  function requestedUrl(): URL {
    return new URL(fetchMock.mock.calls[0][0] as string);
  }

  const client = () => new AlqoveClient({ baseUrl: 'http://api.test' });

  it('encodes array params with PHP-style brackets', async () => {
    await client().get('/v1/items', { store_id: ['a', 'b'] });

    expect(requestedUrl().searchParams.getAll('store_id[]')).toEqual(['a', 'b']);
    expect(requestedUrl().searchParams.getAll('store_id')).toEqual([]);
  });

  it('encodes a single-element array as an array too', async () => {
    await client().get('/v1/items', { store_id: ['only-one'] });

    expect(requestedUrl().searchParams.getAll('store_id[]')).toEqual(['only-one']);
  });

  it('leaves scalar params alone', async () => {
    await client().get('/v1/items', { q: 'denim', page: '2' });

    const params = requestedUrl().searchParams;
    expect(params.get('q')).toBe('denim');
    expect(params.get('page')).toBe('2');
    expect(params.get('q[]')).toBeNull();
  });

  it('omits empty arrays entirely', async () => {
    await client().get('/v1/items', { brand: [] });

    expect(requestedUrl().search).toBe('');
  });
});
