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

export async function GET(req: NextRequest) {
  const domain = req.nextUrl.searchParams.get("domain")?.trim().toLowerCase();
  const type = (req.nextUrl.searchParams.get("type") ?? "A").toUpperCase();
  if (!domain) return NextResponse.json({ error: "domain required" }, { status: 400 });
  if (!/^[a-zA-Z0-9._\-]+$/.test(domain)) {
    return NextResponse.json({ error: "Invalid domain" }, { status: 400 });
  }

  try {
    let records: unknown[] = [];

    switch (type) {
      case "A":
        records = await dns.resolve4(domain, { ttl: true });
        break;
      case "AAAA":
        records = await dns.resolve6(domain, { ttl: true });
        break;
      case "MX":
        records = await dns.resolveMx(domain);
        break;
      case "NS":
        records = await dns.resolveNs(domain);
        break;
      case "TXT":
        records = (await dns.resolveTxt(domain)).map((r) => r.join(""));
        break;
      case "CNAME":
        records = await dns.resolveCname(domain);
        break;
      case "SOA": {
        const soa = await dns.resolveSoa(domain);
        records = [soa];
        break;
      }
      case "PTR":
        records = await dns.resolvePtr(domain);
        break;
      case "SRV":
        records = await dns.resolveSrv(domain);
        break;
      case "CAA":
        records = await dns.resolveCaa(domain);
        break;
      default:
        return NextResponse.json({ error: `Unsupported type: ${type}` }, { status: 400 });
    }

    return NextResponse.json({ domain, type, records, count: records.length });
  } catch (err: unknown) {
    const msg = err instanceof Error ? err.message : "DNS lookup failed";
    return NextResponse.json({ error: msg, domain, type, records: [], count: 0 }, { status: 200 });
  }
}
