import { NextRequest, NextResponse } from "next/server";
import {
  buildLoginRedirect,
  requiresRegistrationToken,
} from "@/lib/auth/registrationRoutes";

export function middleware(req: NextRequest) {
  const isPrefetch =
    req.headers.get("next-router-prefetch") === "1" ||
    req.headers.get("purpose") === "prefetch";

  // prefetch بدون کوکی نباید redirect به /login کش شود
  if (isPrefetch) {
    return NextResponse.next();
  }

  const token = req.cookies.get("token")?.value?.trim();
  const pathname = req.nextUrl.pathname;

  // صفحاتی که ذاتاً نیازمند ورود هستند (حساب کاربری و ساخت محتوا)
  const protectedPaths = ["/settings", "/new-post", "/new-project"];
  const needsAuth = protectedPaths.some((p) => pathname.startsWith(p));

  if (needsAuth && !token) {
    const loginUrl = new URL("/login", req.url);
    loginUrl.searchParams.set("redirect", pathname);
    return NextResponse.redirect(loginUrl);
  }

  // مراحل میانی ثبت‌نام بدون توکن → ورود
  if (requiresRegistrationToken(pathname) && !token) {
    return NextResponse.redirect(
      new URL(buildLoginRedirect(pathname), req.url)
    );
  }

  return NextResponse.next();
}

export const config = {
  matcher: [
    "/settings/:path*",
    "/new-post/:path*",
    "/new-project/:path*",
    "/register/username",
    "/register/password",
    "/register/fullname",
    "/register/complete",
    "/register/usertype",
  ],
};
 