import { NextRequest, NextResponse } from "next/server";
import { verifySessionToken, SESSION_COOKIE } from "@/lib/session";
import { access } from "@/lib/users";
import { readApps } from "@/lib/registry";

export const dynamic = "force-dynamic";

/**
 * nginx `auth_request` endpoint — the domain-wide wall + per-app ACL. nginx calls
 * this (forwarding the user's cookies) before proxying any request; the original
 * target is passed as the `X-Original-URI` header.
 *
 *   200 → allow      401 → not logged in (nginx redirects to /login)
 *   403 → logged in but not allowed this app
 */
export async function GET(req: NextRequest): Promise<NextResponse> {
  const original = req.headers.get("x-original-uri") || req.nextUrl.searchParams.get("path") || "/";
  const pathname = original.split("?")[0];

  // The login flow + assets must be reachable without a session.
  if (isPublic(pathname)) return ok();

  const user = await verifySessionToken(req.cookies.get(SESSION_COOKIE)?.value);
  if (!user) return deny(401);

  const acc = await access(user.email);

  // Hub admin area.
  if (pathname === "/admin" || pathname.startsWith("/admin/")) {
    return acc.admin ? ok() : deny(403);
  }

  // A registered POC app under /<slug> needs the slug in the user's allowlist
  // (admins / "*" bypass). Anything else is a hub route → any logged-in user.
  const slug = (pathname.split("/").filter(Boolean)[0] || "").toLowerCase();
  if (slug) {
    const registered = new Set((await readApps()).map((a) => a.slug));
    if (registered.has(slug)) {
      return acc.all || acc.apps.includes(slug) ? ok() : deny(403);
    }
  }
  return ok();
}

function ok() {
  return new NextResponse(null, { status: 200 });
}
function deny(status: 401 | 403) {
  return new NextResponse(status === 401 ? "unauthenticated" : "forbidden", { status });
}
function isPublic(p: string): boolean {
  return (
    p === "/login" ||
    p.startsWith("/login/") ||
    p.startsWith("/api/auth") ||
    p.startsWith("/api/authz") ||
    p.startsWith("/_next") ||
    p === "/favicon.ico" ||
    p === "/robots.txt"
  );
}
