import { NextMiddleware, NextResponse } from "next/server"

import { findLang } from "./constants/languages"
import * as authRequired from "./middlewares/authRequired"
import * as cmsContent from "./middlewares/cmsContent"
import * as currentWebLogin from "./middlewares/currentWebLogin"
import * as currentWebLogout from "./middlewares/currentWebLogout"
import * as handleAuth from "./middlewares/handleAuth"
import * as myPages from "./middlewares/myPages"
import * as webView from "./middlewares/webView"

export const middleware: NextMiddleware = async (request, event) => {
  const lang = findLang(request.nextUrl.pathname)
  if (!lang) {
    // Lang is required for all our middleware.
    // Without it we shortcircuit early.
    // We use middleware-error route because notFound() requires a root layout
    // which we do not want. We can move to that once all Current stuff is gone.
    return NextResponse.rewrite(
      new URL(`/${lang}/middleware-error/404`, request.nextUrl),
      {
        status: 404,
        statusText: "Not found",
      }
    )
  }

  const middlewares = [
    currentWebLogin,
    currentWebLogout,
    authRequired,
    handleAuth,
    myPages,
    webView,
    cmsContent,
  ]

  try {
    for (let i = 0; i < middlewares.length; ++i) {
      const middleware = middlewares[i]

      if (middleware.matcher(request)) {
        const result = await middleware.middleware(request, event)
        const _continue = result?.headers.get("x-continue")
        if (_continue) {
          continue
        }
        return result
      }
    }
  } catch (e) {
    if (e instanceof NextResponse && e.status) {
      const cause = await e.json()
      console.error(`Error in middleware`)
      console.error(cause)

      return NextResponse.rewrite(
        new URL(`/${lang}/middleware-error/${e.status}`, request.nextUrl),
        {
          status: e.status,
          statusText: e.statusText,
        }
      )
    }

    console.error(`Error in middleware`)
    console.error(e)
    return NextResponse.rewrite(
      new URL(`/${lang}/middleware-error/500`, request.nextUrl),
      {
        status: 500,
        statusText: "Internal Server Error",
      }
    )
  }

  // Follow through with normal App router rules.
  return NextResponse.next()
}

// See "Matching Paths" below to learn more
export const config = {
  /**
   *  Copied from Clerk to protect all routes by default and handle
   *  public routes inside middleware.
   *  (https://clerk.com/docs/quickstarts/nextjs?utm_source=sponsorship&utm_medium=youtube&utm_campaign=code-with-antonio&utm_content=12-31-2023#add-authentication-to-your-app)
   */
  matcher: ["/((?!.+\\.[\\w]+$|_next|.netlify|en/test|api|trpc).*)"],
}
