import { NextResponse } from "next/server"

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

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

  // Public routes that don't require authentication
  const publicRoutes = [
    "/login",
    "/register",
    "/forgot-password",
    "/api/auth",
    "/portal-login",
  ]
  const isPublicRoute = publicRoutes.some((route) =>
    nextUrl.pathname.startsWith(route)
  )

  // Portal routes — allow without admin auth (mock for now)
  const isPortalRoute = nextUrl.pathname.startsWith("/portal")

  if (isPublicRoute || isPortalRoute) {
    // If user is already authenticated and tries to access login, redirect based on role
    if (isAuthenticated && nextUrl.pathname.startsWith("/login")) {
      const role = req.auth?.user?.role
      const redirectPath = getRedirectForRole(role)
      return NextResponse.redirect(new URL(redirectPath, nextUrl))
    }
    return NextResponse.next()
  }

  // Redirect unauthenticated users to login
  if (!isAuthenticated) {
    const loginUrl = new URL("/login", nextUrl)
    loginUrl.searchParams.set("callbackUrl", nextUrl.pathname)
    return NextResponse.redirect(loginUrl)
  }

  return NextResponse.next()
})

function getRedirectForRole(role: string | undefined): string {
  switch (role) {
    case "ADMIN":
    case "STAFF":
    case "PREVENTION_OFFICER":
      return "/dashboard"
    case "MEMBER":
      return "/portal/dashboard"
    default:
      return "/dashboard"
  }
}

export const config = {
  matcher: [
    // Protect all routes EXCEPT:
    // - /login, /register, /forgot-password (auth pages)
    // - /portal-login (portal auth page)
    // - /api/auth (NextAuth API routes)
    // - /_next/static, /_next/image (Next.js internals)
    // - /favicon.ico, /images, /icons (public assets)
    // - /manifest.json, /sw.js, /offline (PWA assets — MUST be public, otherwise the
    //   browser fetches them unauthenticated, gets a 307→/login HTML page, and:
    //   (1) parses the HTML as JSON → "manifest.json:1 Syntax error",
    //   (2) registers an HTML "sw.js" or keeps a STALE service worker in control →
    //       cached old bundles keep serving → "website hasn't changed" after redeploys.
    // - /pricing, /impressum, /datenschutz, /agb (public marketing pages)
    "/((?!login|register|forgot-password|portal-login|api/auth|_next/static|_next/image|favicon.ico|images|icons|manifest.json|sw.js|offline|pricing|impressum|datenschutz|agb).*)",
  ],
}
