import { APIEvent } from "@solidjs/start/server/types";
import { generateState } from "arctic";
import httpStatus from "http-status";
import { setCookie } from "vinxi/http";
import { discord } from "~/lib/auth";

if (typeof import.meta.env.PROD === "undefined")
  throw new Error("No env PROD found!");

export async function GET(event: APIEvent) {
  const state = generateState();
  const url = await discord.createAuthorizationURL(state, {
    scopes: ["identify", "guilds", "guilds.members.read"],
  });

  setCookie(event, "discord_oauth_state", state, {
    path: "/",
    secure: import.meta.env.PROD,
    httpOnly: true,
    maxAge: 60 * 10,
    sameSite: "lax",
  });

  return new Response(null, {
    status: httpStatus.FOUND,
    headers: { Location: url.toString() },
  });
}
