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/[personId] — load', () => {
	it('returns sender history from API', async () => {
		const personId = '123e4567-e89b-12d3-a456-426614174000';
		mockApi.GET.mockResolvedValue({
			response: { ok: true },
			data: { runs: [], personNames: { [personId]: 'Anna Müller' } }
		});

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

		expect(result.history.personNames?.[personId]).toBe('Anna Müller');
	});

	it('throws 404 when person not found', async () => {
		mockApi.GET.mockResolvedValue({
			response: { ok: false, status: 404 },
			error: { code: 'PERSON_NOT_FOUND' }
		});

		await expect(
			load({
				params: { personId: 'unknown-id' },
				fetch,
				request: new Request('http://localhost/admin/ocr/unknown-id'),
				url: new URL('http://localhost/admin/ocr/unknown-id')
			} as never)
		).rejects.toMatchObject({ status: 404 });
	});
});
