import { decode } from "@auth/core/jwt";
import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";

// NextAuth v5 u development-u koristi neprefixovano ime kolačića
const COOKIE_NAME = "authjs.session-token";

export async function proxy(request: NextRequest) {
  const isLoginPage = request.nextUrl.pathname === "/login";

  const sessionToken = request.cookies.get(COOKIE_NAME)?.value;
  let isLoggedIn = false;

  if (sessionToken && process.env.AUTH_SECRET) {
    try {
      const decoded = await decode({
        token: sessionToken,
        secret: process.env.AUTH_SECRET,
        salt: COOKIE_NAME,
      });
      isLoggedIn = !!decoded;
    } catch {
      isLoggedIn = false;
    }
  }

  if (!isLoggedIn && !isLoginPage) {
    const loginUrl = new URL("/login", request.nextUrl.origin);
    loginUrl.searchParams.set("callbackUrl", request.nextUrl.pathname);
    return NextResponse.redirect(loginUrl);
  }

  if (isLoggedIn && isLoginPage) {
    return NextResponse.redirect(new URL("/", request.nextUrl.origin));
  }

  const reqHeaders = new Headers(request.headers);
  reqHeaders.set("x-pathname", request.nextUrl.pathname);
  return NextResponse.next({ request: { headers: reqHeaders } });
}

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