<?php

namespace App\Console\Commands;

use App\Models\Contact;
use App\Services\EmailDeliverabilityChecker;
use Illuminate\Console\Command;

/**
 * Sweeps subscribed contacts for domains that can't receive mail (no MX/A
 * record, or an explicit Null MX) and flips them to 'bounced' so future
 * campaigns skip them automatically. Useful after a bulk import, or to
 * clean up contacts that predate the pre-send bounce check.
 */
class CheckContactDeliverability extends Command
{
    protected $signature = 'contacts:check-deliverability {--dry-run : Report without updating anything}';

    protected $description = 'Flag subscribed contacts whose email domain cannot receive mail as bounced';

    public function handle(): int
    {
        $dryRun = (bool) $this->option('dry-run');

        $contacts = Contact::where('status', 'subscribed')->get(['id', 'email']);
        $flagged  = 0;

        foreach ($contacts as $contact) {
            $reason = EmailDeliverabilityChecker::reason($contact->email);

            if (!$reason) {
                continue;
            }

            $flagged++;
            $this->line("  {$contact->email} - {$reason}");

            if (!$dryRun) {
                $contact->update(['status' => 'bounced']);
                $contact->logActivity('email_bounced', "Marked bounced by deliverability sweep - {$reason}");
            }
        }

        $this->info(($dryRun ? '[dry-run] ' : '') . "{$flagged} of {$contacts->count()} subscribed contacts flagged as bounced.");

        return self::SUCCESS;
    }
}
