<?php

namespace App\Services;

class EmailDeliverabilityChecker
{
    /**
     * Returns a bounce reason when the recipient's domain can't receive
     * mail at all, or null when it looks deliverable. Covers both "no mail
     * server" (no MX, no A/AAAA fallback per RFC 5321) and an explicit
     * Null MX ("0 .", RFC 7505) - a domain can resolve fine and still
     * declare it accepts no mail, which is what example.com/.net/.org do.
     *
     * This only rules out domain-level bounces. A real domain with a
     * nonexistent mailbox (e.g. a typo'd Gmail address) can't be detected
     * this way - that requires an ESP bounce webhook or IMAP polling of a
     * bounce mailbox.
     */
    public static function reason(string $email): ?string
    {
        $domain = substr((string) strrchr($email, '@'), 1);

        if ($domain === '') {
            return 'Invalid email address.';
        }

        $hosts = [];
        if (getmxrr($domain, $hosts)) {
            $hosts = array_map(fn ($h) => rtrim($h, '.'), $hosts);

            if (empty(array_filter($hosts))) {
                return "Domain \"{$domain}\" explicitly refuses mail (Null MX record).";
            }

            return null;
        }

        if (checkdnsrr($domain, 'A') || checkdnsrr($domain, 'AAAA')) {
            return null;
        }

        return "Domain \"{$domain}\" does not exist or has no mail server (no MX/A record).";
    }
}
