<?php

namespace App\Notifications\Traits;

use Illuminate\Support\Facades\Log;

/**
 * Trait to handle notification channels with database priority.
 * 
 * This ensures that database notifications are always saved even if
 * email delivery fails due to mail server configuration issues.
 */
trait SafeMailNotification
{
    /**
     * Get the notification's delivery channels.
     * Database is prioritized first to ensure in-app notifications
     * are saved even if email fails.
     *
     * @param  object  $notifiable
     * @return array
     */
    public function via(object $notifiable): array
    {
        $channels = ['database'];
        
        // Only add mail channel if mail is configured
        if ($this->isMailConfigured()) {
            $channels[] = 'mail';
        }
        
        return $channels;
    }

    /**
     * Check if mail is properly configured.
     *
     * @return bool
     */
    protected function isMailConfigured(): bool
    {
        $mailer = config('mail.default');
        
        // Check if using a real mail service
        if (in_array($mailer, ['log', 'array'])) {
            return false;
        }
        
        // For SMTP, check if host is configured
        if ($mailer === 'smtp') {
            return !empty(config('mail.mailers.smtp.host'));
        }
        
        return true;
    }

    /**
     * Determine if the notification should be sent.
     *
     * @param  object  $notifiable
     * @param  string  $channel
     * @return bool
     */
    public function shouldSend(object $notifiable, string $channel): bool
    {
        // Always send database notifications
        if ($channel === 'database') {
            return true;
        }
        
        // For mail, check if the notifiable has an email
        if ($channel === 'mail') {
            return !empty($notifiable->email);
        }
        
        return true;
    }
}
