/**
 * Next.js Edge Middleware — Admin authentication guard.
 *
 * Runs on the server (Edge runtime) before every /admin request.
 * Reads the `drivehub_admin_session` cookie that is set by the login page.
 *
 * Rules
 * ─────
 *   /admin/login  + cookie present  →  307 /admin          (skip re-login)
 *   /admin/*      + cookie absent   →  307 /admin/login    (unauthenticated)
 *   anything else                   →  pass through
 *
 * IMPORTANT: sessionStorage is NOT readable here (server-side).
 * The login page sets both a cookie AND sessionStorage so that:
 *   - this middleware can protect routes server-side (cookie)
 *   - the React layout can guard client-side navigations (sessionStorage/cookie)
 */

import { NextRequest, NextResponse } from "next/server";

// Keep in sync with lib/adminAuth.ts — inlined here so the Edge runtime
// never needs to evaluate the browser-globals in that file.
const ADMIN_COOKIE_NAME = "drivehub_admin_session";
const LOGIN_PATH        = "/admin/login";
const ADMIN_ROOT        = "/admin";

export function middleware(request: NextRequest) {
  const { pathname } = request.nextUrl;

  // Only guard /admin routes
  if (!pathname.startsWith(ADMIN_ROOT)) {
    return NextResponse.next();
  }

  const token   = request.cookies.get(ADMIN_COOKIE_NAME)?.value ?? null;
  const isLogin = pathname === LOGIN_PATH;

  console.log(
    "[ADMIN_MIDDLEWARE] path=%s token=%s",
    pathname,
    token ? "present" : "absent",
  );

  // ── Case 1: visiting login page while already authenticated ───────────────
  if (isLogin && token) {
    console.log("[ADMIN_REDIRECT] /admin/login → /admin  (cookie present)");
    return NextResponse.redirect(new URL(ADMIN_ROOT, request.url));
  }

  // ── Case 2: visiting protected page without a token ──────────────────────
  if (!isLogin && !token) {
    console.log("[ADMIN_REDIRECT] %s → /admin/login  (no cookie)", pathname);
    // Preserve the intended destination so we can redirect back after login
    const loginUrl = new URL(LOGIN_PATH, request.url);
    if (pathname !== ADMIN_ROOT) {
      loginUrl.searchParams.set("from", pathname);
    }
    return NextResponse.redirect(loginUrl);
  }

  // ── Case 3: everything else is fine ──────────────────────────────────────
  return NextResponse.next();
}

export const config = {
  // Match /admin and all sub-paths.
  // /admin/:path* alone does NOT match the bare /admin path, so list both.
  matcher: ["/admin", "/admin/:path*"],
};
