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

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

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

export const middleware: NextMiddleware = (request) => {
  const url = getPublicNextURL(request)
  const { searchParams } = url

  let modified = false

  if (searchParams.has("fromDate")) {
    const value = searchParams.get("fromDate")
    searchParams.delete("fromDate")
    searchParams.set("fromdate", value!)
    modified = true
  }

  if (searchParams.has("toDate")) {
    const value = searchParams.get("toDate")
    searchParams.delete("toDate")
    searchParams.set("todate", value!)
    modified = true
  }

  if (modified) {
    url.search = searchParams.toString()
    return NextResponse.redirect(url, {
      status: 308,
    })
  }

  return NextResponse.next()
}

export const matcher: MiddlewareMatcher = (request) => {
  const { searchParams } = request.nextUrl
  return searchParams.has("fromDate") || searchParams.has("toDate")
}
