import { describe, expect, it, vi, beforeEach } from 'vitest';

vi.mock('$lib/shared/api.server', () => ({
	createApiClient: vi.fn(),
	extractErrorCode: (e: unknown) => (e as { code?: string } | undefined)?.code
}));
vi.mock('$env/dynamic/private', () => ({ env: { API_INTERNAL_URL: 'http://test-backend:8080' } }));

import { load } from './+page.server';
import { createApiClient } from '$lib/shared/api.server';

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

// ─── happy path ───────────────────────────────────────────────────────────────

describe('document detail load — happy path', () => {
	it('returns document on success', async () => {
		vi.mocked(createApiClient).mockReturnValue({
			GET: vi.fn().mockResolvedValue({
				response: { ok: true, status: 200 },
				data: { id: '123', title: 'Testbrief' }
			})
		} as ReturnType<typeof createApiClient>);

		const mockFetch = vi.fn();

		const result = await load({
			params: { id: '123' },
			fetch: mockFetch as unknown as typeof fetch,
			request: new Request('http://localhost/documents/123'),
			url: new URL('http://localhost/documents/123')
		});

		expect(result.document.title).toBe('Testbrief');
	});
});

// ─── error paths ──────────────────────────────────────────────────────────────

describe('document detail load — error paths', () => {
	it('throws 404 when document does not exist', async () => {
		vi.mocked(createApiClient).mockReturnValue({
			GET: vi.fn().mockResolvedValue({
				response: { ok: false, status: 404 },
				error: null
			})
		} as ReturnType<typeof createApiClient>);

		const mockFetch = vi.fn();

		await expect(
			load({
				params: { id: 'missing' },
				fetch: mockFetch as unknown as typeof fetch,
				request: new Request('http://localhost/documents/123'),
				url: new URL('http://localhost/documents/123')
			})
		).rejects.toMatchObject({ status: 404 });
	});

	it('throws 403 when document is forbidden', async () => {
		vi.mocked(createApiClient).mockReturnValue({
			GET: vi.fn().mockResolvedValue({
				response: { ok: false, status: 403 },
				error: null
			})
		} as ReturnType<typeof createApiClient>);

		const mockFetch = vi.fn();

		await expect(
			load({
				params: { id: 'secret' },
				fetch: mockFetch as unknown as typeof fetch,
				request: new Request('http://localhost/documents/123'),
				url: new URL('http://localhost/documents/123')
			})
		).rejects.toMatchObject({ status: 403 });
	});

	it('redirects to /login on 401', async () => {
		vi.mocked(createApiClient).mockReturnValue({
			GET: vi.fn().mockResolvedValue({
				response: { ok: false, status: 401 },
				error: null
			})
		} as ReturnType<typeof createApiClient>);

		const mockFetch = vi.fn();

		await expect(
			load({
				params: { id: 'any' },
				fetch: mockFetch as unknown as typeof fetch,
				request: new Request('http://localhost/documents/123'),
				url: new URL('http://localhost/documents/123')
			})
		).rejects.toMatchObject({ location: '/login' });
	});
});
