import { NextRequest, NextResponse } from "next/server";
import { exec } from "child_process";
import { promisify } from "util";

const execAsync = promisify(exec);

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

  // Sanitize: only allow safe domain/IP chars
  if (!/^[a-zA-Z0-9._\-]+$/.test(domain)) {
    return NextResponse.json({ error: "Invalid domain format" }, { status: 400 });
  }

  try {
    const { stdout, stderr } = await execAsync(`whois "${domain}"`, { timeout: 15000 });
    const raw = stdout || stderr || "";

    // Try to parse key fields
    const get = (pattern: RegExp) => raw.match(pattern)?.[1]?.trim() ?? null;

    const parsed = {
      domainName: get(/Domain Name:\s*(.+)/i) ?? domain,
      registrar: get(/Registrar:\s*(.+)/i),
      registrarUrl: get(/Registrar URL:\s*(.+)/i),
      createdDate: get(/Creation Date:\s*(.+)/i) ?? get(/Registered on:\s*(.+)/i),
      updatedDate: get(/Updated Date:\s*(.+)/i) ?? get(/Last updated:\s*(.+)/i),
      expiryDate: get(/Registry Expiry Date:\s*(.+)/i) ?? get(/Expiry date:\s*(.+)/i),
      status: raw.match(/Domain Status:\s*(.+)/gi)?.map((s) => s.replace(/Domain Status:\s*/i, "").trim()) ?? [],
      nameservers: raw.match(/Name Server:\s*(.+)/gi)?.map((s) => s.replace(/Name Server:\s*/i, "").trim().toLowerCase()) ?? [],
      dnssec: get(/DNSSEC:\s*(.+)/i),
      registrantName: get(/Registrant Name:\s*(.+)/i) ?? get(/Registrant Organization:\s*(.+)/i),
      registrantCountry: get(/Registrant Country:\s*(.+)/i),
      adminEmail: get(/Admin Email:\s*(.+)/i),
    };

    return NextResponse.json({ domain, parsed, raw });
  } catch (err: unknown) {
    const msg = err instanceof Error ? err.message : "whois failed";
    return NextResponse.json({ error: msg }, { status: 500 });
  }
}
