import type { DiscordScheduledEvent } from './types' const DISCORD_API = 'https://discord.com/api/v10' async function discordFetch(path: string, options: { headers: Record query?: Record }): Promise { for (let attempt = 0; attempt < 3; attempt++) { try { return await $fetch(`${DISCORD_API}${path}`, options) } catch (error: unknown) { const status = (error as { statusCode?: number }).statusCode ?? (error as { status?: number }).status if (status === 429 && attempt < 2) { const retryAfter = (error as { data?: { retry_after?: number } }).data?.retry_after ?? 2 await new Promise(resolve => setTimeout(resolve, Math.min(retryAfter * 1000, 10_000))) continue } throw error } } throw new Error('Max retries exceeded') } export async function fetchGuildEvents(guildId: string): Promise { const cacheKey = `cache:events:${guildId}` const cached = await useStorage('kv').getItem(cacheKey) if (cached) return cached const config = useRuntimeConfig() const events = await discordFetch( `/guilds/${guildId}/scheduled-events`, { headers: { Authorization: `Bot ${config.discordBotToken}` }, query: { with_user_count: true }, }, ) await useStorage('kv').setItem(cacheKey, events, { ttl: 60 }) return events } export async function fetchGuildInfo(guildId: string): Promise<{ id: string, name: string, icon: string | null } | null> { const cacheKey = `cache:guild-info:${guildId}` const cached = await useStorage('kv').getItem<{ id: string, name: string, icon: string | null }>(cacheKey) if (cached) return cached try { const config = useRuntimeConfig() const info = await discordFetch<{ id: string, name: string, icon: string | null }>( `/guilds/${guildId}`, { headers: { Authorization: `Bot ${config.discordBotToken}` }, }, ) await useStorage('kv').setItem(cacheKey, info, { ttl: 300 }) return info } catch { return null } } export async function checkBotInGuild(guildId: string): Promise { const cacheKey = `cache:bot-in-guild:${guildId}` const cached = await useStorage('kv').getItem(cacheKey) if (cached !== null) return cached try { const config = useRuntimeConfig() await discordFetch(`/guilds/${guildId}`, { headers: { Authorization: `Bot ${config.discordBotToken}` }, }) await useStorage('kv').setItem(cacheKey, true, { ttl: 300 }) return true } catch { return false } } export function buildBotInviteUrl(guildId?: string): string { const config = useRuntimeConfig() const params = new URLSearchParams({ client_id: config.oauth.discord.clientId, permissions: '0', scope: 'bot', ...(guildId ? { guild_id: guildId } : {}), }) return `https://discord.com/oauth2/authorize?${params.toString()}` }