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

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

/* 
Middleware function to normalize date formats to support
YYYY-MM-D and YYYY-MM-DD since the current web uses YYYY-MM-D 
in the URL as parameters (toDate and fromDate)
*/
export const middleware: NextMiddleware = (request) => {
  const url = request.nextUrl.clone()
  const { searchParams } = url

  function normalizeDate(date: string): string {
    const datePattern = /^\d{4}-\d{1,2}-\d{1,2}$/
    if (datePattern.test(date)) {
      const [year, month, day] = date.split("-").map(Number)
      return `${year}-${String(month).padStart(2, "0")}-${String(day).padStart(2, "0")}`
    }
    return date
  }

  if (searchParams.has("fromDate")) {
    const fromDate = searchParams.get("fromDate")!
    searchParams.set("fromDate", normalizeDate(fromDate))
  }

  if (searchParams.has("toDate")) {
    const toDate = searchParams.get("toDate")!
    searchParams.set("toDate", normalizeDate(toDate))
  }

  return NextResponse.rewrite(url)
}

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