import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";

const isInfluencerJobDetailPath = (pathName: string) =>
  /^\/influencer\/jobs\/[^/]+$/.test(pathName);

/** Allow social crawlers through so shared job links still get og:* metadata. */
const isLinkPreviewBot = (userAgent: string) =>
  /facebookexternalhit|facebot|twitterbot|linkedinbot|whatsapp|slackbot|discordbot|telegrambot|pinterest|embedly|googlebot|skypeuripreview|microsoft-preview|microsoftpreview|msoffice|ms-office|teams|bingbot/i.test(
    userAgent,
  );

export function proxy(request: NextRequest) {
  const pathName: any = request.nextUrl.pathname;
  const cookies: any = request.cookies;
  const userInfoCookie = cookies.get("user_info");
  const parseUserInfo = userInfoCookie && JSON.parse(userInfoCookie.value);
  const publicJobDetailPath = isInfluencerJobDetailPath(pathName);

  const adminAuth = [
    "/admin/login",
    "/admin/forgot-password",
  ];

  const userAuth = [
    "/login",
    "/forgot-password",
    "/verify-otp",
    "/reset-password",
    "/register",
    "/privacy-policy",
    "/terms-and-conditions",
    "/.well-known/assetlinks.json",
    "/register/influencer",
    "/register/brand",
    "/apple-app-site-association"
  ];

  const rolesAuth = [
    "/register/influencer/verify-otp",
    "/register/brand/verify-otp"
  ];

  const brandStepsPath = [
    "/register/brand/steps"
  ];

  const influencerStepsPath = [
    "/register/influencer/steps",
  ];

  // Helper function to create redirect response with pending_redirect cookie
  const createLoginRedirect = (originalUrl: URL) => {
    const loginUrl = new URL("/login", originalUrl);

    if (originalUrl.pathname.startsWith("/oauth")) {
      originalUrl.searchParams.forEach((value, key) => {
        loginUrl.searchParams.set(key, value);
      });
    }

    const response = NextResponse.redirect(loginUrl);
    // Store the original URL (pathname + search params) in a cookie
    const redirectPath = originalUrl.pathname + originalUrl.search;
    if (redirectPath && redirectPath !== "/login" && !userAuth.includes(redirectPath)) {

      console.log("redirectPath", redirectPath);
      response.cookies.set("pending_redirect", redirectPath, {
        maxAge: 60 * 60, // 1 hour
        httpOnly: false, // Allow client-side access
        secure: process.env.NODE_ENV === "production",
        sameSite: "lax"
      });
    }

    return response;
  };

  if (publicJobDetailPath) {
    // Brand users must never see influencer job details.
    if (cookies.has("bat") || parseUserInfo?.role === "brand") {
      return NextResponse.redirect(new URL("/brand/dashboard", request.url));
    }

    // Logged-out visitors: only redirect a REAL browser navigation to login.
    // Link-preview crawlers (WhatsApp, Facebook, X, etc.) must fall through so
    // generateMetadata can return the job's og:* tags. Browsers send
    // `Sec-Fetch-Dest: document` on top-level navigations; crawlers do not, so
    // any non-document request is treated as a preview fetch and let through.
    if (!cookies.has("iat")) {
      const userAgent = request.headers.get("user-agent") ?? "";
      const isBrowserNavigation =
        request.headers.get("sec-fetch-dest") === "document";

      if (isBrowserNavigation && !isLinkPreviewBot(userAgent)) {
        return createLoginRedirect(request.nextUrl);
      }
    }
  }

  if (!(pathName.startsWith("/influencers") || pathName.startsWith("/sitemap") || pathName.startsWith("/robots") || pathName.startsWith("/kol-list"))) {
    if (!(cookies.has("bat") || cookies.has("iat") || cookies.has("aat") || cookies.has("verifyUAT"))) {

      if (
        (!userAuth.includes(pathName) && pathName.startsWith("/influencer")) &&
        (!cookies.has("iat")) &&
        !publicJobDetailPath
      ) {
        // Job detail URLs without login are handled above (crawlers allowed, humans → login)
        return createLoginRedirect(request.nextUrl);
      }
      if ((!userAuth.includes(pathName) && pathName.startsWith("/brand")) && (!cookies.has("bat"))) {
        // Old code: return NextResponse.redirect(new URL("/login", request.url));
        return createLoginRedirect(request.nextUrl);
      }
      if ((!userAuth.includes(pathName) && pathName.startsWith("/admin")) && (!cookies.has("aat"))) {
        // Old code: return NextResponse.redirect(new URL("/login", request.url));
        return createLoginRedirect(request.nextUrl);
      }
      if (influencerStepsPath.includes(pathName) && (!cookies.has("iat") || !cookies.has("verifyUAT"))) {
        // Old code: return NextResponse.redirect(new URL("/login", request.url));
        return createLoginRedirect(request.nextUrl);
      }
      if (brandStepsPath.includes(pathName) && (!cookies.has("bat") || !cookies.has("verifyUAT"))) {
        // Old code: return NextResponse.redirect(new URL("/login", request.url));
        return createLoginRedirect(request.nextUrl);
      }
      if (rolesAuth.includes(pathName) && (!cookies.has("register_email"))) {
        // Old code: return NextResponse.redirect(new URL("/login", request.url));
        return createLoginRedirect(request.nextUrl);
      }

      // Protect OAuth consent page - require authentication
      if (pathName.startsWith("/oauth")) {
        return createLoginRedirect(request.nextUrl);
      }
    }

    if ((cookies.has("bat") || cookies.has("iat") || cookies.has("aat") || cookies.has("verifyUAT"))) {
      if (!cookies.has("forgot_email")) {
        if ((userAuth.includes(pathName) || rolesAuth.includes(pathName))) {

          // Allow login page to load if there's an OAuth `next` param
          const nextParam = request.nextUrl.searchParams.get("next");
          if (nextParam && parseUserInfo?.pending_steps == 3) {
            const consentUrl = new URL("/oauth/consent", request.url);
            // Forward all query params to the consent page
            request.nextUrl.searchParams.forEach((value, key) => {
              consentUrl.searchParams.set(key, value);
            });
            return NextResponse.redirect(consentUrl);
          }

          if (parseUserInfo?.pending_steps < 3) {
            return NextResponse.redirect(new URL(`/register/${parseUserInfo?.role}/steps`, request.url));
          }
          if (parseUserInfo?.pending_steps == 3) {
            return NextResponse.redirect(new URL(`/${parseUserInfo?.role}/dashboard`, request.url));
          }
        }
        if (parseUserInfo?.pending_steps < 3 && brandStepsPath.includes(pathName) && parseUserInfo?.role == 'influencer') {
          return NextResponse.redirect(new URL(`/register/influencer/steps`, request.url));
        }
        if (parseUserInfo?.pending_steps < 3 && influencerStepsPath.includes(pathName) && parseUserInfo?.role == 'brand') {
          return NextResponse.redirect(new URL(`/register/brand/steps`, request.url));
        }
        if (parseUserInfo?.pending_steps == 3 && (brandStepsPath.includes(pathName) || influencerStepsPath.includes(pathName))) {
          return NextResponse.redirect(new URL(`/${parseUserInfo?.role}/dashboard`, request.url));
        }
      }
    }

    if (!(userAuth.includes(pathName) || rolesAuth.includes(pathName) || brandStepsPath.includes(pathName) || influencerStepsPath.includes(pathName) || (pathName.startsWith("/oauth") && request.nextUrl.searchParams.has("next")))) {
      if ((cookies.has("bat") || cookies.has("iat") || cookies.has("aat") || cookies.has("verifyUAT"))) {
        if (parseUserInfo?.pending_steps < 3) {
          return NextResponse.redirect(new URL(`/register/${parseUserInfo?.role}/steps`, request.url));
        }
        if (parseUserInfo?.role == 'brand' && (!pathName.startsWith("/brand") || pathName == "/brand")) {
          return NextResponse.redirect(new URL(`/${parseUserInfo?.role}/dashboard`, request.url));
        }
        if (parseUserInfo?.role == 'influencer' && (!pathName.startsWith("/influencer") || pathName == "/influencer")) {
          return NextResponse.redirect(new URL(`/${parseUserInfo?.role}/dashboard`, request.url));
        }
        if (parseUserInfo?.role == 'admin' && (!pathName.startsWith("/admin") || pathName == "/admin")) {
          return NextResponse.redirect(new URL(`/${parseUserInfo?.role}/dashboard`, request.url));
        }
      }
    }
  }


  return NextResponse.next();
}

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