import { NextResponse, type NextRequest } from "next/server";
import { createServerClient, type CookieOptions } from "@supabase/ssr";

// Protects everything under /admin (except /admin/login) behind Supabase Auth.
// Also keeps the Supabase session cookie refreshed on every request.
export async function middleware(request: NextRequest) {
  const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL;
  const supabaseAnonKey = process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY;

  // Without these env vars set (e.g. not yet added to the Vercel project's
  // Environment Variables), createServerClient throws immediately when
  // constructing the Supabase client, which crashes this middleware on
  // *every* request — including every single page, not just /admin — with
  // 500: MIDDLEWARE_INVOCATION_FAILED. Fail safe instead of crashing the
  // whole site: skip the auth check until Supabase is actually configured.
  if (!supabaseUrl || !supabaseAnonKey) {
    return NextResponse.next();
  }

  let response = NextResponse.next({ request });

  try {
    const supabase = createServerClient(supabaseUrl, supabaseAnonKey, {
      cookies: {
        getAll() {
          return request.cookies.getAll();
        },
        setAll(cookiesToSet: { name: string; value: string; options?: CookieOptions }[]) {
          cookiesToSet.forEach(({ name, value }) => request.cookies.set(name, value));
          response = NextResponse.next({ request });
          cookiesToSet.forEach(({ name, value, options }) =>
            response.cookies.set(name, value, options as CookieOptions)
          );
        },
      },
    });

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

    const { pathname } = request.nextUrl;
    const isLoginPage = pathname === "/admin/login";

    if (pathname.startsWith("/admin") && !isLoginPage && !user) {
      const url = request.nextUrl.clone();
      url.pathname = "/admin/login";
      url.searchParams.set("next", pathname);
      return NextResponse.redirect(url);
    }

    if (isLoginPage && user) {
      const url = request.nextUrl.clone();
      url.pathname = "/admin";
      url.search = "";
      return NextResponse.redirect(url);
    }

    return response;
  } catch {
    // Same fail-safe: a transient Supabase error shouldn't take the whole
    // site down.
    return NextResponse.next();
  }
}

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