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

const BOT_USER_AGENT_KEYWORDS = [
  "googlebot",
  "adsbot-google",
  "bingbot",
  "slurp",
  "duckduckbot",
  "baiduspider",
  "yandexbot",
  "sogou",
  "exabot",
  "facebot",
  "ia_archiver",
];

// Sensitive parameters that must be stripped for bots/crawlers
const SENSITIVE_PARAMS = [
  "gclid",
  "gad_source",
  "gad_campaignid",
  "gbraid",
  "wbraid",
  "gclsrc",
];

// Google Ads parameters that need to be persisted in cookies
const PERSISTENT_PARAMS = [
  "gad_campaignid",
  "gad_source",
  "gclid",
  "gbraid",
  "wbraid",
] as const;

const GOOGLE_ADS_PARAMS_COOKIE = "google-ads-params";
const COOKIE_MAX_AGE = 60 * 60 * 24; // 24 hours

/**
 * Checks if the request is from a bot/crawler
 */
function isBot(userAgent: string): boolean {
  return BOT_USER_AGENT_KEYWORDS.some((keyword) => userAgent.includes(keyword));
}

export function middleware(request: NextRequest) {
  try {
    const url = request.nextUrl.clone();
    const hostname = request.headers.get("host") || "";
    
    // Extract subdomain from hostname (e.g., "admin.example.com" -> "admin")
    const subdomain = hostname.split(".")[0];
    const isAdminSubdomain = subdomain === "admin";
    const isAdminPath = url.pathname.startsWith("/admin");
    
    // If on admin subdomain, handle admin routing
    if (isAdminSubdomain) {
      // If accessing root path on admin subdomain, rewrite to /admin page
      if (url.pathname === "/" || url.pathname === "") {
        const rewriteUrl = url.clone();
        rewriteUrl.pathname = "/admin";
        return NextResponse.rewrite(rewriteUrl);
      }
      // Allow all other paths (API routes, _next, etc.) - skip bot detection
      return NextResponse.next();
    }
    
    // If accessing /admin on main domain, redirect to admin subdomain
    if (isAdminPath) {
      // Detect protocol (check x-forwarded-proto first, then use https as default)
      const protocol = request.headers.get("x-forwarded-proto") || 
                       (request.url.startsWith("https") ? "https" : "http");
      
      // Extract main domain (handle port if present)
      const mainDomain = hostname.includes(":") 
        ? hostname.split(":")[0] 
        : hostname;
      
      // Build admin subdomain URL
      const adminDomain = `admin.${mainDomain}`;
      const port = hostname.includes(":") ? `:${hostname.split(":")[1]}` : "";
      const pathWithoutAdmin = url.pathname.replace("/admin", "") || "/";
      const redirectUrl = `${protocol}://${adminDomain}${port}${pathWithoutAdmin}${url.search}`;
      
      return NextResponse.redirect(redirectUrl, 301);
    }

    const userAgent = request.headers.get("user-agent")?.toLowerCase() ?? "";
    const isBotRequest = isBot(userAgent);
    const visitorType = isBotRequest ? "bot" : "human";

    const requestHeaders = new Headers(request.headers);
    requestHeaders.set("x-visitor-type", visitorType);

    // For bots/crawlers: Strip sensitive parameters from the URL to prevent indexing
    // This ensures search engines never see Google Ads parameters, mobile flags, etc.
    if (isBotRequest && request.nextUrl.searchParams.size > 0) {
      const cleanUrl = request.nextUrl.clone();
      
      // Remove all sensitive parameters
      SENSITIVE_PARAMS.forEach((param) => {
        cleanUrl.searchParams.delete(param);
      });
      
      // Redirect bots to clean URL (301 permanent redirect for SEO)
      // This ensures bots never index URLs with sensitive params
      return NextResponse.redirect(cleanUrl, {
        status: 301,
        headers: requestHeaders,
      });
    }

    // Persist Google Ads parameters in cookie for non-bot requests
    const response = NextResponse.next({
      request: {
        headers: requestHeaders,
      },
    });

    // Check if request has Google Ads parameters to persist
    const params: Record<string, string> = {};
    let hasAnyParam = false;

    for (const param of PERSISTENT_PARAMS) {
      const value = request.nextUrl.searchParams.get(param);
      if (value) {
        params[param] = value;
        hasAnyParam = true;
      }
    }

    if (hasAnyParam) {
      // Store parameters in cookie as JSON
      response.cookies.set(GOOGLE_ADS_PARAMS_COOKIE, JSON.stringify(params), {
        path: "/",
        maxAge: COOKIE_MAX_AGE,
        sameSite: "lax",
        httpOnly: false, // Allow client-side access if needed
        secure: process.env.NODE_ENV === "production",
      });
    }

    return response;
  } catch (error) {
    // Fallback: return next response on error to prevent middleware failures
    console.error("Middleware error:", error);
    return NextResponse.next();
  }
}

export const config = {
  matcher: [
    /*
     * Match all request paths except for the ones starting with:
     * - api (API routes)
     * - _next/static (static files)
     * - _next/image (image optimization files)
     * - favicon.ico (favicon file)
     * - robots.txt (robots file)
     * - sitemap.xml (sitemap file)
     */
    "/((?!_next/static|_next/image|favicon.ico|robots.txt|sitemap.xml).*)",
  ],
};

