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

// In-memory rate limiter store (resets on server restart)
const rateLimitStore = new Map<string, { count: number; resetTime: number }>();

function getRateLimit(key: string, limit: number, windowMs: number): boolean {
  const now = Date.now();
  const record = rateLimitStore.get(key);

  if (!record || now > record.resetTime) {
    rateLimitStore.set(key, { count: 1, resetTime: now + windowMs });
    return true;
  }

  if (record.count >= limit) {
    return false;
  }

  record.count++;
  return true;
}

function checkAdminAuth(request: NextRequest): boolean {
  const adminToken = request.cookies.get("admin_token")?.value;
  if (!adminToken) return false;

  try {
    const parsed = JSON.parse(adminToken);
    return parsed && parsed.role === "admin" && parsed.email;
  } catch {
    return false;
  }
}

export function middleware(request: NextRequest) {
  const { pathname } = request.nextUrl;
  const response = NextResponse.next();

  // Skip middleware entirely for NextAuth internal routes
  if (pathname.startsWith("/api/auth/")) {
    return response;
  }

  // === SECURITY HEADERS (HTML pages only, not API routes) ===
  if (!pathname.startsWith("/api/")) {
    response.headers.set("X-Frame-Options", "DENY");
    response.headers.set("X-Content-Type-Options", "nosniff");
    response.headers.set("X-XSS-Protection", "1; mode=block");
    response.headers.set("Referrer-Policy", "strict-origin-when-cross-origin");
    response.headers.set("Permissions-Policy", "camera=(), microphone=(), geolocation=(), payment=()");
    response.headers.delete("X-Powered-By");
  }

  // === RATE LIMITING ===
  const ip = request.headers.get("x-forwarded-for")?.split(",")[0] || request.headers.get("x-real-ip") || "unknown";

  // Login: 10 attempts per minute
  if (pathname === "/api/auth/callback/credentials" && request.method === "POST") {
    const key = `login:${ip}`;
    if (!getRateLimit(key, 10, 60000)) {
      return NextResponse.json(
        { error: "تم حظر تسجيل الدخول مؤقتاً." },
        { status: 429 }
      );
    }
  }

  // Admin login: 5 attempts per minute
  if (pathname === "/api/admin/auth/login" && request.method === "POST") {
    const key = `admin-login:${ip}`;
    if (!getRateLimit(key, 5, 60000)) {
      return NextResponse.json(
        { error: "تم حظر تسجيل الدخول مؤقتاً." },
        { status: 429 }
      );
    }
  }

  // File upload: 20 per minute
  if (pathname === "/api/upload" && request.method === "POST") {
    const key = `upload:${ip}`;
    if (!getRateLimit(key, 20, 60000)) {
      return NextResponse.json(
        { error: "تم تجاوز الحد المسموح للتحميل." },
        { status: 429 }
      );
    }
  }

  // Only rate-limit custom auth endpoints, NOT NextAuth internal routes
  if (pathname === "/api/auth/register" && request.method === "POST") {
    const key = `register:${ip}`;
    if (!getRateLimit(key, 3, 600000)) {
      return NextResponse.json(
        { error: "تم تجاوز الحد المسموح لعمليات التسجيل." },
        { status: 429 }
      );
    }
  }

  if (pathname === "/api/auth/forgot-password" && request.method === "POST") {
    const key = `forgot:${ip}`;
    if (!getRateLimit(key, 3, 300000)) {
      return NextResponse.json(
        { error: "تم تجاوز الحد المسموح. يرجى المحاولة بعد 5 دقائق." },
        { status: 429 }
      );
    }
  }

  if (pathname === "/api/auth/verify-email" && request.method === "POST") {
    const key = `verify:${ip}`;
    if (!getRateLimit(key, 5, 60000)) {
      return NextResponse.json(
        { error: "تم تجاوز الحد المسموح لمحاولات التحقق." },
        { status: 429 }
      );
    }
  }

  // === ADMIN API PROTECTION ===
  if (pathname.startsWith("/api/admin/") && !pathname.startsWith("/api/admin/auth/")) {
    if (!checkAdminAuth(request)) {
      return NextResponse.json(
        { error: "غير مصرح. يرجى تسجيل الدخول كمدير." },
        { status: 401 }
      );
    }
  }

  // === ADMIN PAGES PROTECTION (server-side redirect) ===
  if (pathname.startsWith("/ai.admin") && !pathname.startsWith("/ai.admin/login")) {
    if (!checkAdminAuth(request)) {
      return NextResponse.redirect(new URL("/ai.admin/login", request.url));
    }
  }

  return response;
}

export const config = {
  matcher: [
    // Match all paths except static files and Next.js internals
    "/((?!_next/static|_next/image|favicon.ico|uploads/).*)",
  ],
};
