import apiFetch, { type ApiError, type FullGuild } from "$lib/api";
import { error } from "@sveltejs/kit";

export const load = async ({ params }) => {
	try {
		const guild = await apiFetch<FullGuild>(
			"GET",
			`/api/guilds/${params.guildId}`,
		);

		const options = [];

		const channelsWithoutCategory = guild.channels_without_category.filter(
			(c) => c.can_log_to,
		);
		if (channelsWithoutCategory.length > 0)
			options.push({
				label: "(no category)",
				options: channelsWithoutCategory.map((c) => ({
					value: c.id,
					label: `#${c.name}`,
				})),
			});

		options.push(
			...guild.categories
				.map((cat) => ({
					label: cat.name,
					options: cat.channels
						.filter((c) => c.can_log_to)
						.map((c) => ({ value: c.id, label: `#${c.name}` })),
				}))
				.filter((c) => c.options.length > 0),
		);

		return { guild, options };
	} catch (e) {
		const err = e as ApiError;
		console.log("Fetching guild", params.guildId, ":", e);
		error(404, err.message);
	}
};
