import { NextResponse } from "next/server"

import { findLang } from "@/constants/languages"
import { env } from "@/env/server"
import { badRequest, internalServerError } from "@/server/errors/next"

import type { NextMiddleware } from "next/server"

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)!

  if (!env.PUBLIC_URL) {
    throw internalServerError("No value for env.PUBLIC_URL")
  }
  const redirectTo = env.PUBLIC_URL

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

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