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

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

import { findLang } from "@/utils/languages"

import { getDefaultRequestHeaders } from "./utils"

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

export const middleware: NextMiddleware = async (request) => {
  const lang = findLang(request.nextUrl.pathname)!
  const nextUrlPublic = getPublicNextURL(request)
  const redirectUrl = new URL(`/${lang}`, nextUrlPublic)

  const key = request.nextUrl.searchParams.get("key")
  const code = request.nextUrl.searchParams.get("code")

  const md5 = require("md5")
  if (
    key &&
    code &&
    key === md5("scandic" + new Date().toISOString().substring(0, 10))
  ) {
    const headers = new Headers()
    // Set cookie for this device/user to be valid to use the FnF code for 3 days starting now
    headers.append(
      "set-cookie",
      `sc=1; max-age=259200; Path=/; HttpOnly; SameSite=Lax`
    )
    const redirectOpts = {
      headers,
    }
    redirectUrl.searchParams.set("bookingCode", code)
    return NextResponse.redirect(redirectUrl, redirectOpts)
  }

  const headers = getDefaultRequestHeaders(request)
  return NextResponse.redirect(redirectUrl, {
    headers,
  })
}

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