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

describe('/documents/bulk-edit +page.server.ts', () => {
	it('redirects to /documents when user lacks WRITE_ALL', async () => {
		const locals = { user: { groups: [{ permissions: ['READ_ALL'] }] } };
		try {
			// @ts-expect-error — partial event shape sufficient for this guard
			await load({
				locals,
				request: new Request('http://localhost/documents/bulk-edit'),
				url: new URL('http://localhost/documents/bulk-edit')
			});
			throw new Error('expected redirect to be thrown');
		} catch (e) {
			const err = e as { status?: number; location?: string };
			expect(err.status).toBe(303);
			expect(err.location).toBe('/documents');
		}
	});

	it('redirects when user has no groups', async () => {
		const locals = { user: { groups: [] } };
		try {
			// @ts-expect-error — partial event shape sufficient for this guard
			await load({
				locals,
				request: new Request('http://localhost/documents/bulk-edit'),
				url: new URL('http://localhost/documents/bulk-edit')
			});
			throw new Error('expected redirect');
		} catch (e) {
			expect((e as { status?: number }).status).toBe(303);
		}
	});

	it('redirects when no user is logged in', async () => {
		const locals = {};
		try {
			// @ts-expect-error — partial event shape sufficient for this guard
			await load({
				locals,
				request: new Request('http://localhost/documents/bulk-edit'),
				url: new URL('http://localhost/documents/bulk-edit')
			});
			throw new Error('expected redirect');
		} catch (e) {
			expect((e as { status?: number }).status).toBe(303);
		}
	});

	it('returns canWrite=true for a WRITE_ALL user', async () => {
		const locals = { user: { groups: [{ permissions: ['WRITE_ALL', 'READ_ALL'] }] } };
		// @ts-expect-error — partial event shape sufficient for this guard
		const result = await load({
			locals,
			request: new Request('http://localhost/documents/bulk-edit'),
			url: new URL('http://localhost/documents/bulk-edit')
		});
		expect(result).toEqual({ canWrite: true });
	});

	it('redirects when a group has no permissions array (defensive)', async () => {
		// Sara C7 — a UserGroup row with NULL permissions used to throw on
		// .includes(); the guard now treats that case as "not WRITE_ALL".
		const locals = {
			user: { groups: [{ permissions: undefined as unknown as string[] }] }
		};
		try {
			// @ts-expect-error — partial event shape sufficient for this guard
			await load({
				locals,
				request: new Request('http://localhost/documents/bulk-edit'),
				url: new URL('http://localhost/documents/bulk-edit')
			});
			throw new Error('expected redirect');
		} catch (e) {
			expect((e as { status?: number }).status).toBe(303);
		}
	});
});
