import { DiscordGuild } from "next-auth";
import { fixGuildPFP } from "src/utils/discord/fixGuildPFP";
import { getQuestBotGuildIds } from "../questBot/guildBackend";
export async function getDiscordGuilds(
accessToken: string | undefined,
tokenType: string | undefined
) {
const response = await fetch("https://discord.com/api/users/@me/guilds", {
headers: {
Authorization: `${tokenType} ${accessToken}`,
},
});
const allGuilds = await response.json();
const questBotGuildIds = await getQuestBotGuildIds();
// Get all guilds that the user is in that also have QuestBot installed or owns the guild
for (let i = 0; i < allGuilds.length; i++) {
await fixGuildPFP(allGuilds[i]);
if (allGuilds[i].owner === true) {
allGuilds[i].memberType = "admin";
} else {
allGuilds[i].memberType = "user";
}
}
const guildsWithQuestBotAndOwned = allGuilds.filter(
(guild: { id: string; owner: boolean }) =>
questBotGuildIds.includes(guild.id) && guild.owner === true
);
const guildsOwned = allGuilds.filter(
(guild: { id: string; owner: boolean }) =>
guild.owner === true && !questBotGuildIds.includes(guild.id)
);
const guildsWithQuestBot = allGuilds.filter(
(guild: { id: string; owner: boolean }) =>
questBotGuildIds.includes(guild.id) && guild.owner === false
);
const guilds: DiscordGuild[] = guildsWithQuestBotAndOwned.concat(guildsOwned, guildsWithQuestBot);
console.log(guilds)
return guilds;
}