import { NextResponse } from "next/server"

import { auth } from "@/lib/auth"
import { SIGN_IN_URL } from "@/lib/constants"

export default auth((req) => {
  const isLogged = !!req.auth
  const { pathname } = req.nextUrl

  if (isLogged && pathname === SIGN_IN_URL) {
    const newUrl = new URL("/", req.nextUrl.origin)
    return NextResponse.redirect(newUrl)
  }

  if (!isLogged && pathname !== SIGN_IN_URL && pathname !== "/") {
    const newUrl = new URL(SIGN_IN_URL, req.nextUrl.origin)
    newUrl.searchParams.set("callbackUrl", pathname + req.nextUrl.search)
    return NextResponse.redirect(newUrl)
  }

  return NextResponse.next()
})

export const config = {
  matcher: [
    /*
     * Match all request paths except for the ones starting with:
     * - api (API routes)
     * - _next/static (static files)
     * - _next/image (image optimization files)
     * - favicon.ico, sitemap.xml, robots.txt (metadata files)
     */
    "/((?!api|_next/static|_next/image|favicon.ico|sitemap.xml|robots.txt).*)",
  ],
}
