import { NextResponse } from "next/server"

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

import type { NextMiddleware } from "next/server"

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

export const middleware: NextMiddleware = (request) => {
  const returnUrl = request.nextUrl.searchParams.get("returnurl")

  if (!returnUrl) {
    return badRequest()
  }

  const lang = findLang(request.nextUrl.pathname)!

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

  return NextResponse.rewrite(new URL(`/${lang}/login`, request.nextUrl), {
    request: {
      headers,
    },
  })
}

export const matcher: MiddlewareMatcher = (request) => {
  return request.nextUrl.pathname.endsWith("/updatelogin")
}
