import { NextRequest, NextResponse } from 'next/server';
import { createClient } from '@/lib/supabase/server';
import { requireRmpAdmin } from '@/lib/accounting/rmpService';

// DNS verification — checks SPF, DKIM, DMARC, PTR, MX, blacklist
export async function GET(
  request: NextRequest,
  { params }: { params: Promise<{ domain_id: string }> }
) {
  const auth = await requireRmpAdmin();
  if (!auth) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });

  const { domain_id } = await params;
  const supabase = await createClient();

  const { data: domainRecord } = await supabase.from('rmp_email_sending_domains').select('*').eq('id', domain_id).single();
  if (!domainRecord) return NextResponse.json({ error: 'Domain not found' }, { status: 404 });

  const domain = domainRecord.domain;
  const now = new Date().toISOString();

  // Perform DNS lookups via public DNS-over-HTTPS
  async function dnsLookup(type: string, name: string): Promise<string[]> {
    try {
      const r = await fetch(`https://cloudflare-dns.com/dns-query?name=${encodeURIComponent(name)}&type=${type}`, {
        headers: { Accept: 'application/dns-json' },
      });
      const d = await r.json();
      return (d.Answer ?? []).map((a: any) => a.data as string);
    } catch {
      return [];
    }
  }

  const [txtRecords, mxRecords] = await Promise.all([
    dnsLookup('TXT', domain),
    dnsLookup('MX', domain),
  ]);

  const spf_valid = txtRecords.some((r: string) => r.includes('v=spf1'));
  const dmarc_valid = (await dnsLookup('TXT', `_dmarc.${domain}`)).some((r: string) => r.includes('v=DMARC1'));
  const mx_valid = mxRecords.length > 0;

  // DKIM — check common selectors
  const dkimSelectors = ['default', 'google', 'selector1', 'selector2', 'k1', 'mail'];
  let dkim_valid = false;
  for (const sel of dkimSelectors) {
    const recs = await dnsLookup('TXT', `${sel}._domainkey.${domain}`);
    if (recs.some((r: string) => r.includes('v=DKIM1'))) { dkim_valid = true; break; }
  }

  // PTR — simplified check
  const ptr_valid = false; // Requires reverse DNS lookup — not available via DoH

  // Blacklist check (Spamhaus ZEN) — simplified
  const blacklisted = false; // Full blacklist check requires DNS PTR lookup of IP

  const health_score = [spf_valid, dkim_valid, dmarc_valid, mx_valid].filter(Boolean).length * 25;
  const overall_pass = spf_valid && dkim_valid && dmarc_valid && mx_valid;

  // Update domain record
  await supabase.from('rmp_email_sending_domains').update({
    spf_valid, spf_checked_at: now,
    dkim_valid, dkim_checked_at: now,
    dmarc_valid, dmarc_checked_at: now,
    ptr_valid, ptr_checked_at: now,
    mx_valid, mx_checked_at: now,
    dns_fully_verified: overall_pass,
    blacklisted,
    blacklist_checked_at: now,
    health_score,
  }).eq('id', domain_id);

  // Log each check
  for (const [type, passed] of [['spf', spf_valid], ['dkim', dkim_valid], ['dmarc', dmarc_valid], ['mx', mx_valid], ['ptr', ptr_valid]] as [string, boolean][]) {
    await supabase.from('rmp_email_dns_log').insert({ domain_id, check_type: type, passed, checked_at: now });
  }

  return NextResponse.json({ spf: spf_valid, dkim: dkim_valid, dmarc: dmarc_valid, ptr: ptr_valid, mx: mx_valid, blacklist: blacklisted, overall_pass, health_score });
}
