<?php

namespace App\Services\Notifications;

use App\Models\Customer;
use App\Models\ReminderNotificationLog;
use Illuminate\Support\Facades\Mail;
use Throwable;

class EmailReminderProvider implements ReminderChannelProvider
{
    public function send(ReminderNotificationLog $log, Customer $customer): NotificationDeliveryResult
    {
        if(blank($customer->email)) return NotificationDeliveryResult::failed('Customer email address is missing.');
        $mailer=(string)config('mail.default','');
        if(in_array($mailer,['','log','array'],true)) return NotificationDeliveryResult::failed('A real email delivery transport is not configured.');

        try {
            Mail::raw($log->message,function($message) use ($log): void {
                $message->to($log->recipient)->subject($log->subject ?: 'Loan payment reminder');
            });
            return NotificationDeliveryResult::delivered(json_encode(['transport'=>$mailer],JSON_UNESCAPED_SLASHES));
        } catch(Throwable $e) {
            return NotificationDeliveryResult::failed($e->getMessage());
        }
    }
}
