<?php

namespace App\Notifications;

use App\Services\MailSettings;
use Illuminate\Bus\Queueable;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Notifications\Notification;

class VerifyEmailCode extends Notification
{
    use Queueable;

    public function __construct(
        private readonly string $code,
    ) {}

    /**
     * @return array<int, string>
     */
    public function via(object $notifiable): array
    {
        return ['mail'];
    }

    public function toMail(object $notifiable): MailMessage
    {
        $template = collect(app(MailSettings::class)->templates())
            ->firstWhere('key', 'email_verification');

        $replacements = [
            '{{ name }}' => $notifiable->name ?? 'there',
            '{{ verification_code }}' => $this->code,
            '{{ verification_url }}' => route('verification.notice'),
            '{{ dashboard_url }}' => route('dashboard'),
        ];

        if (is_array($template)) {
            $html = strtr($template['html'] ?? '', $replacements);
            $text = strtr($template['text'] ?? '', $replacements);

            if (filled($html)) {
                return (new MailMessage)
                    ->subject($template['subject'] ?? 'Verify your urless account')
                    ->view([
                        'html' => 'emails.raw-html',
                        'text' => 'emails.raw-text',
                    ], [
                        'html' => $html,
                        'text' => $text ?: "Your urless verification code is {$this->code}.",
                    ]);
            }
        }

        return (new MailMessage)
            ->subject('Verify your urless account')
            ->greeting('Verify your email address')
            ->line('Use this verification code to activate your urless account.')
            ->line($this->code)
            ->line('This code expires in 30 minutes.')
            ->action('Open verification page', route('verification.notice'))
            ->line('If you did not create this account, you can safely ignore this email.');
    }
}
