/**
 * ─────────────────────────────────────────────────────────────────────────────
 * NEXT.JS MIDDLEWARE — route protection + security headers
 * ─────────────────────────────────────────────────────────────────────────────
 *
 * Runs on the EDGE before every matched request.
 *
 * Auth logic:
 *  • Public routes (/login, /register, /book/*, /confirm/*, /api/auth/*)
 *    → allowed without a session cookie
 *  • Dashboard routes (/dashboard, /appointments, /leads, etc.)
 *    → require a session cookie (existence check only — full DB validation
 *       happens in each API route / server component via getSession())
 *  • API routes (/api/*)
 *    → protected by the individual route handlers via requireAuth()
 */

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

// ── Public paths (no auth required) ──────────────────────────────────────────
const PUBLIC_PATHS = [
  "/login",
  "/register",
  "/book",
  "/confirm",
  "/api/auth/login",
  "/api/auth/register",
  "/api/auth/logout",
  "/api/auth/oauth",      // all /api/auth/oauth/** routes
  "/api/webhooks",        // WhatsApp webhooks
  "/api/book",            // public booking
  "/api/cron",            // cron jobs (protected by CRON_SECRET internally)
  "/api/test-flow",       // dev tool
  "/api/test-reminders",  // reminder testing (auth handled inside route)
  "/_next",
  "/favicon.ico",
];

const SESSION_COOKIE = "clinera_session";

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

  // ── Security headers (applied to ALL responses) ───────────────────────────
  const res = NextResponse.next();
  res.headers.set("X-Frame-Options",        "DENY");
  res.headers.set("X-Content-Type-Options", "nosniff");
  res.headers.set("Referrer-Policy",        "strict-origin-when-cross-origin");
  res.headers.set("Permissions-Policy",     "camera=(), microphone=(), geolocation=()");

  if (process.env.NODE_ENV === "production") {
    res.headers.set(
      "Strict-Transport-Security",
      "max-age=63072000; includeSubDomains; preload"
    );
  }

  // ── Allow public paths ────────────────────────────────────────────────────
  const isPublic = PUBLIC_PATHS.some((p) => pathname.startsWith(p));
  if (isPublic) return res;

  // ── Check session cookie presence ─────────────────────────────────────────
  // Note: We only check cookie existence here (DB validation is in getSession()).
  // This avoids a DB call on every request while still preventing obvious
  // unauthenticated access.
  const sessionCookie = req.cookies.get(SESSION_COOKIE);

  if (!sessionCookie?.value) {
    // API routes → 401 JSON
    if (pathname.startsWith("/api/")) {
      return new NextResponse(
        JSON.stringify({ error: "Unauthorized" }),
        {
          status:  401,
          headers: { "Content-Type": "application/json" },
        }
      );
    }

    // Page routes → redirect to /login
    const loginUrl = new URL("/login", req.url);
    loginUrl.searchParams.set("next", pathname);
    return NextResponse.redirect(loginUrl);
  }

  // ── Redirect authenticated users away from auth pages ─────────────────────
  // (This is a soft check — getSession() validates the token fully)
  if (pathname === "/login" || pathname === "/register") {
    return NextResponse.redirect(new URL("/dashboard", req.url));
  }

  return res;
}

export const config = {
  matcher: [
    /*
     * Match all paths EXCEPT:
     * - _next/static (static files)
     * - _next/image (image optimization)
     * - favicon.ico
     */
    "/((?!_next/static|_next/image|favicon.ico).*)",
  ],
};
