// ───────────────────────────────────────────────
// Middleware — Route Protection & Auth
// ───────────────────────────────────────────────
// This middleware runs on every incoming request
// (except static assets and public routes). It:
//   1. Skips public routes (login, auth API, etc.)
//   2. Reads the "session" cookie
//   3. Verifies the JWT via @/lib/jwt
//   4. Injects x-user-id / x-user-role headers
//   5. Redirects unauthenticated users to /login
//      (with a ?redirect= param for post-login nav)
// ───────────────────────────────────────────────

import { NextResponse } from "next/server"
import type { NextRequest } from "next/server"
import { verifyToken } from "@/lib/jwt"

/** Routes that do NOT require authentication. */
const publicRoutes = [
  "/login",
  "/api/auth/login",
  "/api/auth/logout",
  "/_next/static",
  "/_next/image",
  "/favicon.ico",
  "/logo",
  "/fonts",
]

/** Name of the cookie that holds the user's JWT session token. */
const SESSION_COOKIE = "session"

/**
 * middleware
 * ──────────
 * Next.js edge middleware. Checks every request
 * against the public-routes whitelist, validates
 * the JWT session cookie, and either allows the
 * request (injecting user context headers) or
 * redirects to the login page.
 *
 * @param request - The incoming NextRequest.
 * @returns NextResponse (next, redirect, or 401 JSON).
 */
export async function middleware(request: NextRequest) {
  const { pathname } = request.nextUrl

  // ── Skip public / static routes ──
  const isPublic = publicRoutes.some(
    (route) => pathname === route || pathname.startsWith(route + "/") || pathname.startsWith(route)
  )

  if (isPublic) {
    return NextResponse.next()
  }

  // ── Read session cookie ──
  const token = request.cookies.get(SESSION_COOKIE)?.value

  // No cookie at all → 401 for API, redirect for pages
  if (!token) {
    if (pathname.startsWith("/api/")) {
      return NextResponse.json({ error: "Unauthorized" }, { status: 401 })
    }
    const loginUrl = new URL("/login", request.url)
    loginUrl.searchParams.set("redirect", pathname)
    return NextResponse.redirect(loginUrl)
  }

  // ── Verify JWT ──
  const payload = await verifyToken(token)
  if (!payload) {
    // Token invalid / expired
    if (pathname.startsWith("/api/")) {
      return NextResponse.json({ error: "Unauthorized" }, { status: 401 })
    }
    const loginUrl = new URL("/login", request.url)
    loginUrl.searchParams.set("redirect", pathname)
    return NextResponse.redirect(loginUrl)
  }

  // ── Attach user context to downstream handlers ──
  const requestHeaders = new Headers(request.headers)
  requestHeaders.set("x-user-id", payload.userId)
  requestHeaders.set("x-user-role", payload.role)

  return NextResponse.next({ request: { headers: requestHeaders } })
}

/** Middleware matcher — excludes Next.js internals and static assets. */
export const config = {
  matcher: ["/((?!_next/static|_next/image|favicon.ico|logo|fonts).*)"],
}
