import { NextRequest, NextResponse } from "next/server";
import { promises as dns } from "dns";

const BLACKLISTS = [
  "zen.spamhaus.org",
  "bl.spamcop.net",
  "b.barracudacentral.org",
  "dnsbl.sorbs.net",
  "dnsbl-1.uceprotect.net",
  "dnsbl-2.uceprotect.net",
  "dnsbl-3.uceprotect.net",
  "spam.dnsbl.sorbs.net",
  "relays.mail-abuse.org",
  "blacklist.woody.ch",
  "bogons.cymru.com",
  "psbl.surriel.com",
  "db.wpbl.info",
  "ix.dnsbl.manitu.net",
  "combined.abuse.ch",
  "cbl.abuseat.org",
  "pbl.spamhaus.org",
  "sbl.spamhaus.org",
  "xbl.spamhaus.org",
  "ubl.unsubscore.com",
];

function reverseIP(ip: string): string {
  return ip.split(".").reverse().join(".");
}

function isValidIPv4(ip: string): boolean {
  return /^(\d{1,3}\.){3}\d{1,3}$/.test(ip);
}

export async function GET(req: NextRequest) {
  const target = req.nextUrl.searchParams.get("target")?.trim();
  if (!target) return NextResponse.json({ error: "target required" }, { status: 400 });

  if (!/^[a-zA-Z0-9._\-]+$/.test(target)) {
    return NextResponse.json({ error: "Invalid input" }, { status: 400 });
  }

  let lookupHost: string;
  const isIP = isValidIPv4(target);

  if (isIP) {
    lookupHost = reverseIP(target);
  } else {
    // For domain, resolve to IP first
    try {
      const [ip] = await dns.resolve4(target);
      lookupHost = reverseIP(ip);
    } catch {
      return NextResponse.json({ error: `Could not resolve ${target} to an IPv4 address` }, { status: 400 });
    }
  }

  const results = await Promise.allSettled(
    BLACKLISTS.map(async (bl) => {
      const query = `${lookupHost}.${bl}`;
      try {
        const addrs = await dns.resolve4(query);
        return { blacklist: bl, listed: true, response: addrs[0] };
      } catch {
        return { blacklist: bl, listed: false, response: null };
      }
    })
  );

  const checks = results.map((r) => (r.status === "fulfilled" ? r.value : { blacklist: "unknown", listed: false, response: null }));
  const listedCount = checks.filter((c) => c.listed).length;

  return NextResponse.json({ target, isIP, lookupHost, checks, listedCount, totalChecked: BLACKLISTS.length });
}
