<?php

declare(strict_types=1);

namespace App\Console\Commands;

use App\Mail\WarrantyExpiryDigest;
use App\Services\WarrantyService;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Str;

/**
 * The daily warranty renewal reminder — `enable_warranty_emails`,
 * `warranty_alert_days` and `warranty_alert_recipients` have all been
 * seeded settings since Phase 0, waiting for this.
 *
 * Runs synchronously (there is no queue) and is scheduled once a day; see
 * `bootstrap/app.php`.
 */
class SendWarrantyExpiryDigest extends Command
{
    /** @var string */
    protected $signature = 'ams:send-warranty-digest';

    /** @var string */
    protected $description = 'Email the configured recipients a digest of warranties expiring soon';

    public function handle(WarrantyService $warranties): int
    {
        if (! setting('enable_warranty_emails', false)) {
            $this->components->info('Warranty digest emails are turned off (Settings → Send Warranty Emails).');

            return self::SUCCESS;
        }

        /** @var array<int, string> $recipients */
        $recipients = array_filter((array) setting('warranty_alert_recipients', []));

        if ($recipients === []) {
            $this->components->warn('No warranty alert recipients are configured — nothing sent.');

            return self::SUCCESS;
        }

        $windows = $warranties->digestData();
        $total = array_sum(array_map(static fn ($w) => $w->count(), $windows));

        if ($total === 0) {
            $this->components->info('No warranties are entering an alert window today — nothing sent.');

            return self::SUCCESS;
        }

        Mail::to($recipients)->send(new WarrantyExpiryDigest($windows));

        $this->components->info(sprintf(
            'Sent a digest covering %d %s to %d %s.',
            $total,
            Str::plural('warranty', $total),
            count($recipients),
            Str::plural('recipient', count($recipients)),
        ));

        return self::SUCCESS;
    }
}
