import { NextResponse } from "next/server"

import { notFound } from "@/server/errors/next"

import { findLang } from "@/utils/languages"
import { removeTrailingSlash } from "@/utils/url"

import { fetchAndCacheEntry, getDefaultRequestHeaders } from "./utils"

import type { NextMiddleware } from "next/server"

import { MiddlewareMatcher } from "@/types/middleware"

export const middleware: NextMiddleware = async (request) => {
  const { nextUrl } = request
  const lang = findLang(nextUrl.pathname)!

  const pathWithoutTrailingSlash = removeTrailingSlash(nextUrl.pathname)

  const contentTypePathName = pathWithoutTrailingSlash.replace(`/${lang}`, "")
  const isPreview = request.nextUrl.pathname.includes("/preview")
  const searchParams = new URLSearchParams(request.nextUrl.searchParams)

  const { contentType, uid } = await fetchAndCacheEntry(
    isPreview
      ? contentTypePathName.replace("/preview", "")
      : contentTypePathName,
    lang
  )

  if (!contentType || !uid) {
    throw notFound(
      `Unable to resolve CMS entry for locale "${lang}": ${contentTypePathName}`
    )
  }
  const headers = getDefaultRequestHeaders(request)
  headers.set("x-uid", uid)
  headers.set("x-contenttype", contentType)

  const isCurrent = contentType ? contentType.indexOf("current") >= 0 : false

  if (isPreview) {
    searchParams.set("isPreview", "true")
    return NextResponse.rewrite(
      new URL(
        `/${lang}/${contentType}/${uid}?${searchParams.toString()}`,
        nextUrl
      ),
      {
        request: {
          headers,
        },
      }
    )
  }

  if (isCurrent) {
    searchParams.set("uid", uid)
    searchParams.set("uri", contentTypePathName)
    return NextResponse.rewrite(
      new URL(
        `/${lang}/current-content-page?${searchParams.toString()}`,
        nextUrl
      ),
      {
        request: {
          headers,
        },
      }
    )
  }

  return NextResponse.rewrite(
    new URL(
      `/${lang}/${contentType}/${uid}?${searchParams.toString()}`,
      nextUrl
    ),
    {
      request: {
        headers,
      },
    }
  )
}

export const matcher: MiddlewareMatcher = (request) => {
  // Do not process paths with file extension.
  // Only looking for dot might be too brute force/give false positives.
  // It works right now but adjust accordingly when new use cases/data emerges.
  const lastPathnameSegment = request.nextUrl.pathname.split("/").pop()
  return lastPathnameSegment?.indexOf(".") === -1
}
