<?php

declare(strict_types=1);

namespace App\Mail;

use App\Domain\Account\Models\Account;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Mail\Mailable;
use Illuminate\Mail\Mailables\Content;
use Illuminate\Mail\Mailables\Envelope;
use Illuminate\Queue\SerializesModels;

class QuotaWarningMail extends Mailable implements ShouldQueue
{
    use Queueable, SerializesModels;

    public function __construct(
        public readonly Account $account,
        public readonly int $quotaBytes,
        public readonly int $usageBytes,
    ) {}

    public function envelope(): Envelope
    {
        $pct = $this->quotaBytes > 0
            ? (int) round($this->usageBytes / $this->quotaBytes * 100)
            : 0;

        return new Envelope(
            subject: "Disk Kotası Uyarısı %{$pct} — ".($this->account->primary_domain ?? $this->account->username),
            tags: ['quota', 'warning'],
        );
    }

    public function content(): Content
    {
        $pct = $this->quotaBytes > 0 ? (int) round($this->usageBytes / $this->quotaBytes * 100) : 0;
        $usedHuman = $this->formatBytes($this->usageBytes);
        $quotaHuman = $this->formatBytes($this->quotaBytes);

        return new Content(
            view: 'emails.quota.warning',
            with: [
                'account' => $this->account,
                'usedPercent' => $pct,
                'usedHuman' => $usedHuman,
                'quotaHuman' => $quotaHuman,
            ],
        );
    }

    private function formatBytes(int $bytes): string
    {
        if ($bytes >= 1073741824) {
            return round($bytes / 1073741824, 1).' GB';
        }
        if ($bytes >= 1048576) {
            return round($bytes / 1048576, 1).' MB';
        }

        return round($bytes / 1024, 1).' KB';
    }
}
