const BOT_TOKEN = process.env.BOT_TOKEN!;
const API = 'https://discord.com/api/v10';

async function discordFetch(endpoint: string) {
  const res = await fetch(`${API}${endpoint}`, {
    headers: { Authorization: `Bot ${BOT_TOKEN}` },
    next: { revalidate: 30 }
  });
  if (!res.ok) return null;
  return res.json();
}

export async function getGuild(guildId: string) {
  return discordFetch(`/guilds/${guildId}?with_counts=true`);
}

export async function getGuildChannels(guildId: string) {
  const channels = await discordFetch(`/guilds/${guildId}/channels`);
  if (!channels) return { textChannels: [], categories: [] };
  return {
    textChannels: channels.filter((c: any) => c.type === 0).sort((a: any, b: any) => a.name.localeCompare(b.name)),
    voiceChannels: channels.filter((c: any) => c.type === 2 || c.type === 13).sort((a: any, b: any) => a.name.localeCompare(b.name)),
    categories: channels.filter((c: any) => c.type === 4).sort((a: any, b: any) => a.name.localeCompare(b.name)),
  };
}

export async function getGuildRoles(guildId: string) {
  const roles = await discordFetch(`/guilds/${guildId}/roles`);
  if (!roles) return [];
  return roles
    .filter((r: any) => !r.managed && r.name !== '@everyone')
    .sort((a: any, b: any) => b.position - a.position)
    .map((r: any) => ({ id: r.id, name: r.name, color: r.color ? `#${r.color.toString(16).padStart(6, '0')}` : '#99aab5' }));
}

export async function getBotGuilds() {
  return discordFetch('/users/@me/guilds') || [];
}
