try {
  process.loadEnvFile(".env.local");
} catch {}

import { getNetworkSecurity } from "../lib/admin/network-security";
import { formatLocationDisplay, buildLocationFromBigDataCloud } from "../lib/admin/location-formatter";
import { db } from "../lib/admin/db";
import { createAdminSession } from "../lib/admin/auth";

async function runAllSecurityTests() {
  console.log("==================================================");
  console.log("QUTO AI ADMIN: COMPREHENSIVE SECURITY TEST SUITE");
  console.log("==================================================");

  // ----------------------------------------------------
  // TEST 1: Network Security Abstraction & Signals
  // ----------------------------------------------------
  console.log("\n[TEST 1] Testing getNetworkSecurity signals & policy...");

  // 1A: Normal IP (localhost)
  const normalNet = await getNetworkSecurity("127.0.0.1");
  console.log("1A. Local dev IP:", {
    ip: normalNet.ip,
    isVpn: normalNet.isVpn,
    isBlocked: normalNet.isBlocked,
    risk: normalNet.risk,
  });
  if (normalNet.isBlocked || normalNet.isVpn) {
    throw new Error("FAIL: Localhost was unexpectedly blocked");
  }

  // 1B: Simulated VPN
  const vpnReq = new Request("http://localhost:3000", {
    headers: { "x-simulate-vpn": "true" },
  });
  const vpnNet = await getNetworkSecurity("203.0.113.195", vpnReq as any);
  console.log("1B. Simulated VPN:", {
    ip: vpnNet.ip,
    isVpn: vpnNet.isVpn,
    isBlocked: vpnNet.isBlocked,
    reason: vpnNet.blockReason,
  });
  if (!vpnNet.isBlocked || !vpnNet.isVpn) {
    throw new Error("FAIL: VPN was not detected/blocked");
  }

  // 1C: Simulated Proxy
  const proxyReq = new Request("http://localhost:3000", {
    headers: { "x-simulate-vpn": "proxy" },
  });
  const proxyNet = await getNetworkSecurity("198.51.100.42", proxyReq as any);
  console.log("1C. Simulated Proxy:", {
    ip: proxyNet.ip,
    isProxy: proxyNet.isProxy,
    isBlocked: proxyNet.isBlocked,
    reason: proxyNet.blockReason,
  });
  if (!proxyNet.isBlocked || !proxyNet.isProxy) {
    throw new Error("FAIL: Proxy was not detected/blocked");
  }

  // 1D: Simulated Tor
  const torReq = new Request("http://localhost:3000", {
    headers: { "x-simulate-vpn": "tor" },
  });
  const torNet = await getNetworkSecurity("198.51.100.77", torReq as any);
  console.log("1D. Simulated Tor:", {
    ip: torNet.ip,
    isTor: torNet.isTor,
    isBlocked: torNet.isBlocked,
    reason: torNet.blockReason,
  });
  if (!torNet.isBlocked || !torNet.isTor) {
    throw new Error("FAIL: Tor was not detected/blocked");
  }

  console.log("✓ TEST 1 PASSED: All network security signals accurately evaluated.\n");

  // ----------------------------------------------------
  // TEST 2: Location Formatter & Degradation Strategy
  // ----------------------------------------------------
  console.log("[TEST 2] Testing Location Formatter and Fallbacks...");

  // 2A: Full address
  const fullLoc = {
    status: "available" as const,
    latitude: 26.88403,
    longitude: 75.74335,
    locality: "Mansarovar",
    city: "Jaipur",
    region: "Rajasthan",
    country: "India",
    source: "browser-geolocation-reverse-geocode",
  };
  const strFull = formatLocationDisplay(fullLoc);
  console.log("2A. Full address display:", strFull);
  if (strFull !== "Mansarovar, Jaipur, Rajasthan, India") {
    throw new Error(`FAIL: Unexpected full address: ${strFull}`);
  }

  // 2B: Duplicate locality/city
  const dupLoc = {
    status: "available" as const,
    locality: "Jaipur",
    city: "Jaipur",
    region: "Rajasthan",
    country: "India",
  };
  const strDup = formatLocationDisplay(dupLoc);
  console.log("2B. Deduplication check (Jaipur, Jaipur):", strDup);
  if (strDup !== "Jaipur, Rajasthan, India") {
    throw new Error(`FAIL: Duplicate parts not removed: ${strDup}`);
  }

  // 2C: Coordinate fallback (reverse geocode unavailable)
  const coordOnlyLoc = {
    status: "available" as const,
    latitude: 26.88403,
    longitude: 75.74335,
  };
  const strCoord = formatLocationDisplay(coordOnlyLoc);
  console.log("2C. Coordinate-only fallback:", strCoord);
  if (!strCoord.includes("26.8840, 75.7434")) {
    throw new Error(`FAIL: Coordinates not preserved: ${strCoord}`);
  }

  // 2D: Location Denied
  const deniedLoc = { status: "denied" as const };
  console.log("2D. Denied status display:", formatLocationDisplay(deniedLoc));
  if (formatLocationDisplay(deniedLoc) !== "Location access denied") {
    throw new Error("FAIL: Denied status not handled");
  }

  console.log("✓ TEST 2 PASSED: Location display accurately formatted without street fabrication.\n");

  // ----------------------------------------------------
  // TEST 3: Database Session Storage & Audit Logging
  // ----------------------------------------------------
  console.log("[TEST 3] Testing Database Session & Audit Logs...");

  const users = await db.getUsers();
  const mainAdmin = users.find((u) => u.level === "MAIN_ADMIN") || users[0];
  if (!mainAdmin) {
    throw new Error("No admin user found in database");
  }

  // 3A: Create legitimate session with NetworkSecurityInfo attached
  const { session: legitimateSession } = await createAdminSession(mainAdmin.id, {
    ip: "127.0.0.1",
    userAgent: "Mozilla/5.0 (Windows NT 10.0; Win64; x64) Chrome/130.0",
    networkSecurity: normalNet,
  });

  const retrievedSession = await db.getSessionByTokenHash(legitimateSession.tokenHash);
  console.log("3A. Session created with network security:", {
    sessionId: retrievedSession?.id,
    hasNetworkSecurity: Boolean(retrievedSession?.networkSecurity),
    isBlocked: retrievedSession?.networkSecurity?.isBlocked,
  });
  if (!retrievedSession?.networkSecurity || retrievedSession.networkSecurity.isBlocked) {
    throw new Error("FAIL: Legitimate session network security record mismatch");
  }

  // 3B: Simulate VPN detected on existing session -> Revocation & Audit Log
  await db.updateSessionNetworkSecurity(legitimateSession.tokenHash, vpnNet);
  await db.revokeSession(
    legitimateSession.tokenHash,
    "SYSTEM",
    vpnNet.blockReason || "Commercial VPN connection detected"
  );

  const revokedSession = await db.getSessionByTokenHash(legitimateSession.tokenHash);
  console.log("3B. Session query after revocation:", {
    sessionActive: Boolean(revokedSession),
  });
  if (revokedSession !== null) {
    throw new Error("FAIL: Revoked session was still returned as active by getSessionByTokenHash");
  }
  console.log("✓ Session successfully revoked and invalidated.");

  // 3C: Create NETWORK_SECURITY_BLOCKED audit log entry
  const auditLog = await db.createAuditLog({
    action: "NETWORK_SECURITY_BLOCKED",
    status: "FAILURE",
    userId: mainAdmin.id,
    targetType: "SESSION",
    targetId: legitimateSession.id,
    details: {
      reason: vpnNet.blockReason,
      signals: {
        vpn: vpnNet.isVpn,
        proxy: vpnNet.isProxy,
        tor: vpnNet.isTor,
        relay: vpnNet.isRelay,
      },
      provider: vpnNet.provider,
      ip: vpnNet.ip,
      asn: vpnNet.asn,
    },
    location: fullLoc,
    networkSecurity: vpnNet,
    ipAddress: vpnNet.ip,
  });

  console.log("3C. Security Audit Log recorded:", {
    id: auditLog.id,
    action: auditLog.action,
    humanLocation: formatLocationDisplay(auditLog.location),
    signals: auditLog.networkSecurity ? {
      vpn: auditLog.networkSecurity.isVpn,
      proxy: auditLog.networkSecurity.isProxy,
      tor: auditLog.networkSecurity.isTor,
    } : null,
  });
  if (auditLog.action !== "NETWORK_SECURITY_BLOCKED") {
    throw new Error("FAIL: Audit log action mismatch");
  }

  console.log("✓ TEST 3 PASSED: Session revocation & audit logs verified in MongoDB.\n");

  console.log("==================================================");
  console.log("ALL SECURITY TESTS COMPLETED SUCCESSFULLY!");
  console.log("==================================================");
}

runAllSecurityTests()
  .then(() => process.exit(0))
  .catch((e) => {
    console.error("TEST FAILED:", e);
    process.exit(1);
  });
