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

import { getPublicNextURL } from "@/server/utils"

import { getDefaultRequestHeaders } from "./utils"

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

export const middleware: NextMiddleware = async (request) => {
  const headers = getDefaultRequestHeaders(request)

  const newUrl = new URL(
    request.nextUrl.pathname.slice(0, -1),
    getPublicNextURL(request)
  )

  return NextResponse.redirect(newUrl, {
    headers,
    status: 308,
  })
}

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