import { beforeEach, describe, expect, it, vi } from 'vitest';
import { getLanguages } from './languages';

function jsonResponse(body: unknown, status = 200): Response {
  return new Response(JSON.stringify(body), { headers: { 'Content-Type': 'application/json' }, status });
}

describe('getLanguages', () => {
  beforeEach(() => {
    window.localStorage.clear();
    vi.restoreAllMocks();
  });

  it('GETs /api/v1/languages and returns the list', async () => {
    const fetchSpy = vi.spyOn(window, 'fetch').mockResolvedValue(
      jsonResponse([{ code: 'eng', englishName: 'English' }])
    );

    await expect(getLanguages()).resolves.toEqual([{ code: 'eng', englishName: 'English' }]);

    const [url, init] = fetchSpy.mock.calls[0];
    expect(url).toBe('/api/v1/languages');
    expect((init?.method ?? 'GET').toUpperCase()).toBe('GET');
  });

  it('rejects with the ApiError status on failure', async () => {
    vi.spyOn(window, 'fetch').mockResolvedValue(
      jsonResponse({ status: 500, title: 'Internal Server Error' }, 500)
    );

    await expect(getLanguages()).rejects.toMatchObject({ status: 500 });
  });
});
