<?php

declare(strict_types=1);

namespace App\Mail;

use Carbon\CarbonInterface;
use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Mail\Mailables\Content;
use Illuminate\Mail\Mailables\Envelope;
use Illuminate\Queue\SerializesModels;

/**
 * Email алерт админу Лидерры о business-shortfall'е тенанта: snapshot ожидал
 * объём X, фактически доставили Y и (X-Y)/X > порога (20%).
 *
 * Отдельно от CsvDriftAlertMail — тот ловит webhook-loss (CSV vs БД),
 * этот — bizness-drift (snapshot.expected vs delivered).
 *
 * Stage 4 §4.4.4 R-05.
 */
final class TenantBusinessDriftAlertMail extends Mailable
{
    use Queueable;
    use SerializesModels;

    public function __construct(
        public readonly int $tenantId,
        public readonly string $snapshotDate,
        public readonly int $expected,
        public readonly int $delivered,
        public readonly float $shortfallRatio,
        public readonly CarbonInterface $windowStart,
        public readonly CarbonInterface $windowEnd,
    ) {}

    public function envelope(): Envelope
    {
        $pct = number_format($this->shortfallRatio * 100, 1, ',', ' ');

        return new Envelope(
            subject: "Лидерра ↔ Поставщик: business-shortfall tenant #{$this->tenantId} за {$this->snapshotDate} ({$pct}%)",
        );
    }

    public function content(): Content
    {
        return new Content(view: 'emails.tenant_business_drift_alert');
    }
}
