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

import { badRequest } from "@/server/errors/next"
import { getPublicURL } from "@/server/utils"

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

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

export const middleware: NextMiddleware = (request) => {
  const currentwebUrl = request.nextUrl.searchParams.get("currentweb")
  if (currentwebUrl == null || undefined) {
    return badRequest()
  }
  const lang = findLang(request.nextUrl.pathname)!

  const redirectTo = getPublicURL(request)

  const headers = new Headers(request.headers)
  headers.set("x-returnurl", redirectTo)
  headers.set("x-logout-source", "seamless")

  return NextResponse.rewrite(new URL(`/${lang}/logout`, request.nextUrl), {
    request: {
      headers,
    },
  })
}
export const matcher: MiddlewareMatcher = (request) => {
  return request.nextUrl.pathname.endsWith("/updatelogout")
}
