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

import { REDEMPTION, SEARCHTYPE } from "@/constants/booking"
import { login } from "@/constants/routes/handleAuth"
import { getPublicNextURL } from "@/server/utils"

import { auth } from "@/auth"
import { findLang } from "@/utils/languages"
import { isValidSession } from "@/utils/session"

import { getDefaultRequestHeaders } from "./utils"

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

export const middleware: NextMiddleware = async (request) => {
  // Redirect user to login if reward nights search and not logged in
  const isRedemption =
    request.nextUrl.searchParams.get(SEARCHTYPE) === REDEMPTION
  const session = await auth() // Check for user session
  if (isRedemption && !isValidSession(session)) {
    const lang = findLang(request.nextUrl.pathname)!
    const nextUrlPublic = getPublicNextURL(request)
    const headers = new Headers()
    headers.append(
      "set-cookie",
      `redirectTo=${encodeURIComponent(nextUrlPublic.href)}; Path=/; HttpOnly; SameSite=Lax`
    )

    const loginUrl = login[lang]
    const redirectUrl = new URL(loginUrl, nextUrlPublic)
    const redirectOpts = {
      headers,
    }
    return NextResponse.redirect(redirectUrl, redirectOpts)
  }

  const headers = getDefaultRequestHeaders(request)
  return NextResponse.next({
    request: {
      headers,
    },
  })
}

export const matcher: MiddlewareMatcher = (request) => {
  return !!request.nextUrl.pathname.match(
    /^\/(da|de|en|fi|no|sv)\/(hotelreservation)/
  )
}
