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

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

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

function mockApi(groups: unknown[]) {
	vi.mocked(createApiClient).mockReturnValue({
		GET: vi.fn().mockResolvedValueOnce({ response: { ok: true }, data: groups })
	} as ReturnType<typeof createApiClient>);
}

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

describe('admin/groups layout load', () => {
	it('returns the groups list', async () => {
		mockApi([
			{ id: 'g1', name: 'Admins', permissions: ['ADMIN'] },
			{ id: 'g2', name: 'Editors', permissions: ['WRITE_ALL'] }
		]);
		const result = await load({
			fetch: vi.fn() as unknown as typeof fetch,
			request: new Request('http://localhost/admin/groups'),
			url: new URL('http://localhost/admin/groups')
		});
		expect(result.groups).toHaveLength(2);
		expect(result.groups[0].name).toBe('Admins');
	});

	it('returns an empty array when the API returns nothing', async () => {
		mockApi([]);
		const result = await load({
			fetch: vi.fn() as unknown as typeof fetch,
			request: new Request('http://localhost/admin/groups'),
			url: new URL('http://localhost/admin/groups')
		});
		expect(result.groups).toEqual([]);
	});

	it('calls GET /api/groups', async () => {
		const mockGet = vi.fn().mockResolvedValue({ response: { ok: true }, data: [] });
		vi.mocked(createApiClient).mockReturnValue({ GET: mockGet } as ReturnType<
			typeof createApiClient
		>);
		await load({
			fetch: vi.fn() as unknown as typeof fetch,
			request: new Request('http://localhost/admin/groups'),
			url: new URL('http://localhost/admin/groups')
		});
		expect(mockGet).toHaveBeenCalledWith('/api/groups');
	});
});
