// app/api/auth/[auth0]/route.js

import {
  type AfterCallbackAppRoute,
  type AppRouteHandlerFnContext,
  getSession,
  handleAuth,
  handleCallback,
  handleLogin,
  handleLogout,
  type Session,
} from "@auth0/nextjs-auth0"
import { type NextRequest, NextResponse } from "next/server"

const afterCallback: AfterCallbackAppRoute = (req: NextRequest, session: Session) => {
  if (session.user != null) {
    return session;
  }
};

export const GET = handleAuth({
  // eslint-disable-next-line
  login: async (request: any, response: any) => {
    console.log("Logging in")
    try {
      return await handleLogin(request as NextRequest, response as AppRouteHandlerFnContext, {
        returnTo: "/app",
      })
    } catch (error) {
      console.log("Error logging in:", error)
    }
  },
  // eslint-disable-next-line
  logout: async (request: any, response: any) => {
    console.log("Logging out")
    try {
      return await handleLogout(request as NextRequest, response as AppRouteHandlerFnContext, {
        returnTo: "/login",
      })
    } catch (error) {
      console.log("Error logging out:", error)
    }
  },
  // eslint-disable-next-line
  callback: async (req: any, res: any)=> {
    try {
      const response = (await handleCallback(req as NextRequest, res as AppRouteHandlerFnContext, { afterCallback })) as NextResponse;
      const session = await getSession(req as NextRequest, response);
      if (session != null) {
        return NextResponse.redirect(`${process.env.AUTH0_BASE_URL}/app`, response);
      } else {
        // TODO: Unsure where this should redirect to
        return NextResponse.redirect(`${process.env.AUTH0_BASE_URL}/waitlist`, response);
      }  // eslint-disable-next-line
    } catch (error: any) {
      console.log("Error in callback:", error);
      if(error.status === 400 && error.message.search("allowlist-fail") !== -1){
        // write regex parsing and group extraction for the following regex allowlist-fail\s(.*)\s(.*)\)
        const re = /allowlist-fail\s(.*)\s(.*)\)/;
        const match = error.message.match(re);
        if (match != null) {
          const userId = match[1];
          const userNickname = match[2];
          return NextResponse.redirect(`${process.env.AUTH0_BASE_URL}/waitlist?username=${userNickname}&userid=${userId}`, );
        }
      }
    }
  }

  // TODO: Add callback for the waitlist if someone is not on the allowlist
})
