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(users: unknown[]) {
	vi.mocked(createApiClient).mockReturnValue({
		GET: vi.fn().mockResolvedValueOnce({ response: { ok: true }, data: users })
	} as ReturnType<typeof createApiClient>);
}

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

describe('admin/users layout load', () => {
	it('returns the users list', async () => {
		mockApi([
			{ id: 'u1', email: 'alice@example.com' },
			{ id: 'u2', email: 'bob@example.com' }
		]);
		const result = await load({
			fetch: vi.fn() as unknown as typeof fetch,
			request: new Request('http://localhost/admin/users'),
			url: new URL('http://localhost/admin/users')
			// eslint-disable-next-line @typescript-eslint/no-explicit-any
		} as any);
		expect(result.users).toHaveLength(2);
		expect(result.users[0].email).toBe('alice@example.com');
	});

	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/users'),
			url: new URL('http://localhost/admin/users')
			// eslint-disable-next-line @typescript-eslint/no-explicit-any
		} as any);
		expect(result.users).toEqual([]);
	});

	it('calls GET /api/users', 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/users'),
			url: new URL('http://localhost/admin/users')
			// eslint-disable-next-line @typescript-eslint/no-explicit-any
		} as any);
		expect(mockGet).toHaveBeenCalledWith('/api/users');
	});
});
