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

// GET /api/email/domains/verify-all — run daily 6:00 AM
export async function GET(request: NextRequest) {
  const secret = request.headers.get('x-cron-secret') ?? request.nextUrl.searchParams.get('secret');
  if (secret !== process.env.CRON_SECRET) {
    return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
  }

  const supabase = await createClient();
  const { data: domains } = await supabase.from('rmp_email_sending_domains').select('id, domain, dns_fully_verified');

  let verified = 0;
  let failed = 0;

  for (const d of (domains ?? [])) {
    try {
      const r = await fetch(`${process.env.NEXT_PUBLIC_SITE_URL}/api/email/domains/${d.id}/verify`);
      const result = await r.json();
      if (result.overall_pass) verified++;
      else {
        failed++;
        // Alert admin if previously passing domain now fails
        if (d.dns_fully_verified && !result.overall_pass) {
          const notifyEmail = process.env.NOTIFY_EMAIL;
          if (notifyEmail) {
            await fetch(`${process.env.NEXT_PUBLIC_SITE_URL}/api/marketplace/send-email`, {
              method: 'POST',
              headers: { 'Content-Type': 'application/json' },
              body: JSON.stringify({
                to: notifyEmail,
                subject: `RMP DNS Alert: ${d.domain} now failing`,
                text: `Domain ${d.domain} was previously verified but DNS checks are now failing.`,
              }),
            }).catch(() => {});
          }
        }
      }
    } catch {}
  }

  return NextResponse.json({ ok: true, verified, failed });
}
