import { beforeEach, describe, expect, it, vi } from 'vitest';
import { load } from './+page.server';

const mockApi = { GET: vi.fn() };

vi.mock('$lib/shared/api.server', () => ({
	createApiClient: () => mockApi,
	extractErrorCode: (e: unknown) => (e as { code?: string } | undefined)?.code
}));

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

describe('admin/ocr/global — load', () => {
	it('returns history from API', async () => {
		mockApi.GET.mockResolvedValue({
			response: { ok: true },
			data: { runs: [{ id: 'run1' }], personNames: {} }
		});

		const result = (await load({
			fetch,
			request: new Request('http://localhost/admin/ocr/global'),
			url: new URL('http://localhost/admin/ocr/global')
		} as never))!;

		expect(result.history.runs).toHaveLength(1);
	});

	it('throws error when API call fails', async () => {
		mockApi.GET.mockResolvedValue({ response: { ok: false, status: 500 }, error: {} });

		await expect(
			load({
				fetch,
				request: new Request('http://localhost/admin/ocr/global'),
				url: new URL('http://localhost/admin/ocr/global')
			} as never)
		).rejects.toMatchObject({ status: 500 });
	});
});
