import { getLogger } from "@/logger";
import { DiscordAuthProvider } from "@/auth/discord";
import {
  AuthState,
  authTicketOAuth,
  getAuthState,
  getCode,
  getUser
} from "@/auth/auth";

const logger = getLogger("/oauth/discord/redirect");

export async function GET(request: Request) {
  const code = await getCode(request);
  if (code instanceof Response) return code;

  const tokenBody = await DiscordAuthProvider.getToken(code);
  if (tokenBody == null) throw "baby";

  const provider = new DiscordAuthProvider(tokenBody.access_token);
  const id = await provider.getId();
  const permitted = await provider.isPermitted();

  // If someone clicked register on the front page with an existing account,
  // wire it to their user via the auth ticket
  let gluestickId = null;
  const authState = await getAuthState();
  if (authState === AuthState.LoggedIn) {
    const currentUser = await getUser();
    gluestickId = currentUser!.id;
  }

  if (!permitted && gluestickId == null) {
    logger.info({ id }, "user tried to sign up");
    return new Response("not permitted to register account", { status: 403 });
  }

  const userId = await DiscordAuthProvider.update(
    id,
    tokenBody.access_token,
    tokenBody.refresh_token,
    new Date(Date.now() + tokenBody.expires_in * 1000),
    gluestickId ?? undefined
  );

  const [user, authTicket] = await authTicketOAuth(userId);

  if (user?.username !== null) {
    return new Response(null, {
      status: 302,
      headers: {
        "Set-Cookie": `ticket=${authTicket.ticket}; Path=/;`,
        Location: "/me"
      }
    });
  }

  const username = await provider.getDisplayName();
  const email = await provider.getEmail();
  const avatarUrl = await provider.getAvatar();

  const query = new URLSearchParams();
  query.append("username", username);
  query.append("email", email ?? "");
  query.append("avatar", avatarUrl ?? "");

  return new Response(null, {
    status: 302,
    headers: {
      "Set-Cookie": `ticket=${authTicket.ticket}; Path=/;`,
      Location: "/register?" + query.toString()
    }
  });
}
