import { NextResponse, type NextRequest } from "next/server";
import { ROUTES } from "@/lib/constants";
import { env } from "@/lib/env";
import { createClient } from "@/lib/supabase/middleware";

const PUBLIC_PATHS = [ROUTES.login];

function isPublic(pathname: string) {
  return PUBLIC_PATHS.some((path) => pathname === path || pathname.startsWith(`${path}/`));
}

export async function proxy(request: NextRequest) {
  if (env.disableAuth) {
    return NextResponse.next({ request });
  }

  const { client, response } = createClient(request);
  const {
    data: { user },
  } = await client.auth.getUser();

  const pathname = request.nextUrl.pathname;
  if (pathname.startsWith("/api")) {
    return response;
  }

  if (!user && !isPublic(pathname)) {
    const redirectUrl = request.nextUrl.clone();
    redirectUrl.pathname = ROUTES.login;
    redirectUrl.searchParams.set("next", pathname);
    return NextResponse.redirect(redirectUrl);
  }

  if (user && pathname === ROUTES.login) {
    const redirectUrl = request.nextUrl.clone();
    redirectUrl.pathname = ROUTES.dashboard;
    redirectUrl.search = "";
    return NextResponse.redirect(redirectUrl);
  }

  return response;
}

export const config = {
  matcher: [
    "/((?!_next/static|_next/image|favicon.ico|local-thumbnails/|.*\\.(?:svg|png|jpg|jpeg|gif|webp|pdf)$).*)",
  ],
};
