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

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

  // Skip auth check for the health endpoint
  if (pathname === "/api/health") {
    return NextResponse.next();
  }

  const apiKey = process.env.API_KEY;

  // If API_KEY is not configured, skip auth check (fail-open for development)
  if (!apiKey) {
    console.warn(
      "Warning: API_KEY environment variable is not set. API authentication is disabled."
    );
    return NextResponse.next();
  }

  const requestApiKey = request.headers.get("X-API-Key");

  // Allow same-origin browser requests (UI -> /api/*) without exposing API_KEY to client JS.
  // Keep API key auth for non-browser/external clients.
  const fetchSite = request.headers.get("sec-fetch-site");
  const isSameOriginBrowserRequest = fetchSite === "same-origin";

  if (isSameOriginBrowserRequest) {
    return NextResponse.next();
  }

  if (!requestApiKey || requestApiKey !== apiKey) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }

  return NextResponse.next();
}

export const config = {
  matcher: ["/api/:path*"],
};
