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, url }) => {
	const { tags } = await parent();
	const tag = tags.find((t: { id: string }) => t.id === params.id);
	if (!tag) throw error(404, getErrorMessage('TAG_NOT_FOUND'));
	return { tag, mergeSuccess: url.searchParams.has('merged') };
};

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

		const name = data.get('name') as string;
		const parentId = (data.get('parentId') as string) || null;
		const color = (data.get('color') as string) || null;

		const result = await api.PUT('/api/tags/{id}', {
			params: { path: { id: params.id } },
			body: { name, parentId: parentId ?? undefined, color: color ?? undefined }
		});

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

		return { success: true };
	},

	merge: async ({ params, request, fetch }) => {
		const data = await request.formData();
		const targetId = data.get('targetId') as string;
		const api = createApiClient(fetch);

		const result = await api.POST('/api/tags/{id}/merge', {
			params: { path: { id: params.id } },
			body: { targetId }
		});

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

		throw redirect(303, `/admin/tags/${result.data!.id}?merged=1`);
	},

	delete: async ({ params, request, fetch }) => {
		const data = await request.formData();
		const deleteMode = (data.get('deleteMode') as string) || 'single';
		const api = createApiClient(fetch);

		const result =
			deleteMode === 'subtree'
				? await api.DELETE('/api/tags/{id}/subtree', {
						params: { path: { id: params.id } }
					})
				: await api.DELETE('/api/tags/{id}', {
						params: { path: { id: params.id } }
					});

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

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