<?php

declare(strict_types=1);

namespace App\Domain\Notification\Listeners;

use App\Domain\Ssl\Events\SslExpiring;
use App\Domain\Ssl\Events\SslIssued;
use App\Domain\Ssl\Events\SslRenewed;
use App\Domain\Ssl\Models\SslCertificate;
use App\Mail\SslExpiringMail;
use App\Mail\SslIssuedMail;
use Illuminate\Support\Facades\Mail;

class SendSslMails
{
    public function handleIssued(SslIssued $event): void
    {
        $email = $this->resolveRecipient($event->certificate);
        if (! $email) {
            return;
        }

        Mail::to($email)->queue(new SslIssuedMail($event->certificate));
    }

    public function handleRenewed(SslRenewed $event): void
    {
        // Yenileme = tekrar issued ile aynı mail
        $email = $this->resolveRecipient($event->certificate);
        if (! $email) {
            return;
        }

        Mail::to($email)->queue(new SslIssuedMail($event->certificate));
    }

    public function handleExpiring(SslExpiring $event): void
    {
        $email = $this->resolveRecipient($event->certificate);
        if (! $email) {
            return;
        }

        Mail::to($email)->queue(
            new SslExpiringMail($event->certificate, $event->daysUntilExpiry)
        );
    }

    private function resolveRecipient(SslCertificate $cert): ?string
    {
        // SslCertificate -> Domain -> Account -> owner (User) -> email
        $account = $cert->domain?->account ?? null;
        if (! $account) {
            return null;
        }

        return $account->owner?->email ?? null;
    }
}
