import { NextResponse, type NextRequest } from 'next/server'
import { jwtVerify } from 'jose'

const SESSION_COOKIE = 'hha_session'

/** Routes that require a signed-in session. */
const PROTECTED_PREFIXES = [
  '/dashboard',
  '/trips',
  '/history',
  '/billing',
  // Role routes (2026-09-13): <abbr>-dashboard and <abbr>-trip-workspace/<trip number>.
  '/fb-dashboard', '/cd-dashboard', '/pd-dashboard', '/ct-dashboard', '/pc-dashboard', '/fb-new-trip-request', '/fb-new-trip', '/cd-new-trip', '/pd-new-trip',
  '/fb-trip-workspace', '/cd-trip-workspace', '/pd-trip-workspace', '/ct-trip-workspace', '/pc-trip-workspace',
]

async function hasValidSession(request: NextRequest): Promise<boolean> {
  const token = request.cookies.get(SESSION_COOKIE)?.value
  if (!token || !process.env.AUTH_SECRET) return false
  try {
    await jwtVerify(token, new TextEncoder().encode(process.env.AUTH_SECRET))
    return true
  } catch {
    return false
  }
}

/**
 * The proxy only checks that a session cookie is a validly-signed JWT. It
 * cannot see revocation (an admin password reset or role change, 2026-09-11)
 * without a database call on every request, so it deliberately does NOT send
 * `/login` visitors to the dashboard any more: a revoked-but-well-signed
 * cookie would have bounced /login → /dashboard → /login forever. The
 * "already signed in" redirect lives in `app/(auth)/login/layout.tsx`, which
 * uses getSessionUser and therefore respects revocation.
 */
export async function proxy(request: NextRequest) {
  const { pathname } = request.nextUrl

  const needsAuth = PROTECTED_PREFIXES.some((p) => pathname === p || pathname.startsWith(`${p}/`))
  if (!needsAuth) return NextResponse.next()
  if (await hasValidSession(request)) return NextResponse.next()

  const login = request.nextUrl.clone()
  login.pathname = '/login'
  login.search = `?next=${encodeURIComponent(pathname)}`
  return NextResponse.redirect(login)
}

export const config = {
  matcher: [
    '/dashboard/:path*', '/trips/:path*', '/history/:path*', '/billing/:path*', '/dashboard', '/history', '/billing',
    '/fb-dashboard', '/cd-dashboard', '/pd-dashboard', '/ct-dashboard', '/pc-dashboard', '/fb-new-trip-request', '/fb-new-trip', '/cd-new-trip', '/pd-new-trip',
    '/fb-trip-workspace/:path*', '/cd-trip-workspace/:path*', '/pd-trip-workspace/:path*', '/ct-trip-workspace/:path*', '/pc-trip-workspace/:path*',
  ],
}
