import { error, fail, redirect } from '@sveltejs/kit';
import type { PageServerLoad, Actions } from './$types';
import { createApiClient, extractErrorCode } from '$lib/shared/api.server';
import { getErrorMessage } from '$lib/shared/errors';

export const load: PageServerLoad = async ({ params, parent }) => {
	const { groups } = await parent();
	const group = groups.find((g: { id: string }) => g.id === params.id);
	if (!group) throw error(404, getErrorMessage('GROUP_NOT_FOUND'));
	return { group };
};

export const actions: Actions = {
	update: async ({ params, request, fetch }) => {
		const data = await request.formData();
		const api = createApiClient(fetch);

		const result = await api.PATCH('/api/groups/{id}', {
			params: { path: { id: params.id } },
			body: {
				name: data.get('name') as string,
				permissions: data.getAll('permissions') as string[]
			}
		});

		if (!result.response.ok) {
			return fail(result.response.status, {
				error: getErrorMessage(extractErrorCode(result.error))
			});
		}

		return { success: true };
	},

	delete: async ({ params, fetch }) => {
		const api = createApiClient(fetch);
		const result = await api.DELETE('/api/groups/{id}', {
			params: { path: { id: params.id } }
		});

		if (!result.response.ok) {
			return fail(result.response.status, {
				error: getErrorMessage(extractErrorCode(result.error))
			});
		}

		throw redirect(303, '/admin/groups');
	}
};
