import { createServerClient } from "@supabase/ssr";
import { NextResponse, type NextRequest } from "next/server";
import { getSupabaseAnonKey, getSupabaseUrl } from "@/lib/supabase/config";

export async function proxy(request: NextRequest) {
  if (
    request.nextUrl.pathname === "/uploads" ||
    request.nextUrl.pathname.startsWith("/uploads/")
  ) {
    return new NextResponse(null, {
      status: 404,
      headers: {
        "Cache-Control": "no-store",
        "X-Robots-Tag": "noindex, nofollow, noarchive"
      }
    });
  }

  let response = NextResponse.next({ request });
  const url = getSupabaseUrl();
  const key = getSupabaseAnonKey();
  if (!url || !key) return response;

  const supabase = createServerClient(url, key, {
    cookies: {
      getAll: () => request.cookies.getAll(),
      setAll(cookiesToSet) {
        cookiesToSet.forEach(({ name, value }) => request.cookies.set(name, value));
        response = NextResponse.next({ request });
        cookiesToSet.forEach(({ name, value, options }) => response.cookies.set(name, value, options));
      }
    }
  });

  const {
    data: { user }
  } = await supabase.auth.getUser();

  const pathname = request.nextUrl.pathname;
  const isDonorRoute = pathname === "/donor" || pathname.startsWith("/donor/");
  const isSecurityRoute =
    pathname === "/donor/security" || pathname.startsWith("/donor/security/");

  if (user && isDonorRoute && !isSecurityRoute) {
    const { data: profile } = await supabase
      .from("profiles")
      .select("role,must_change_password")
      .eq("id", user.id)
      .maybeSingle();

    if (profile?.role === "donor" && profile.must_change_password) {
      const destination = request.nextUrl.clone();
      destination.pathname = "/donor/security";
      destination.search = "?required=1";
      const redirectResponse = NextResponse.redirect(destination);
      response.cookies.getAll().forEach((cookie) => redirectResponse.cookies.set(cookie));
      return redirectResponse;
    }
  }

  return response;
}

export const config = {
  matcher: ["/((?!_next/static|_next/image|favicon.ico|images/).*)"]
};
