import { v4 } from "uuid";

export type DiscordAccessTokenResponse = {
  access_token: string;
  token_type: string;
  expires_in: number;
  refresh_token: string;
  scope: string;
};

export type DiscordUserResponse = {
  id: string;
  avatar: string | null;
  username: string;
  email: string | null;
};

export type DiscordGuildResponse = {
  id: string;
};

export function discordRedirectUri() {
  return `${process.env.BASE_DOMAIN}oauth/discord/redirect`;
}

export async function getDiscordUser(token: string) {
  const req = await fetch("https://discord.com/api/users/@me", {
    headers: {
      Authorization: `Bearer ${token}`
    }
  });
  const res: DiscordUserResponse = await req.json();
  return res;
}

export async function getDiscordGuilds(token: string) {
  const req = await fetch("https://discord.com/api/users/@me/guilds", {
    headers: {
      Authorization: `Bearer ${token}`
    }
  });
  const res: DiscordGuildResponse[] = await req.json();
  return res.map((guild) => guild.id);
}

export async function getDiscordAvatar(token: string) {
  const req = await fetch("https://discord.com/api/users/@me", {
    headers: {
      Authorization: `Bearer ${token}`
    }
  });

  const res: DiscordUserResponse = await req.json();
  if (res.avatar === null) return null;
  const file = `https://cdn.discordapp.com/avatars/${res.id}/${res.avatar}.png`;
  return file;
}
