import { createApiClient } from '$lib/shared/api.server';
import type { components } from '$lib/generated/api';
import type { LayoutServerLoad } from './$types';

type TagTreeNodeDTO = components['schemas']['TagTreeNodeDTO'];

export type FlatTag = {
	id: string;
	name: string;
	color?: string;
	parentId?: string;
	documentCount: number;
};

function flattenTree(nodes: TagTreeNodeDTO[], result: FlatTag[] = []): FlatTag[] {
	for (const node of nodes) {
		result.push({
			id: node.id!,
			name: node.name!,
			color: node.color ?? undefined,
			parentId: node.parentId ?? undefined,
			documentCount: node.documentCount ?? 0
		});
		if (node.children?.length) flattenTree(node.children, result);
	}
	return result;
}

export const load: LayoutServerLoad = async ({ fetch }) => {
	const api = createApiClient(fetch);
	const result = await api.GET('/api/tags/tree');
	const tree = result.data ?? [];
	return { tree, tags: flattenTree(tree) };
};
