export async function onRequestGet(context: RequestContext) {
  const { env, request } = context;
  const { host, protocol } = new URL(request.url);
  let returnPath = "/";
  const referer = request.headers.get("referer");

  if (referer) {
    const { pathname, search } = new URL(referer);
    returnPath = `${pathname}${search}`;
  } else {
    const { searchParams } = new URL(context.request.url);

    if (searchParams.get("type") === "mobile")
      returnPath = "/api/auth/mobile/token";
  }

  const state = crypto.randomUUID().replaceAll("-", "");

  await env.DATA.put(`state_${state}`, returnPath, { expirationTtl: 300 });

  return Response.redirect(
    `https://discord.com/oauth2/authorize?client_id=${
      env.DISCORD_ID
    }&redirect_uri=${encodeURIComponent(
      `${protocol}//${host}/api/auth/session`,
    )}&response_type=code&scope=identify%20email%20guilds.members.read&state=${state}`,
  );
}
