<?php

namespace Modules\MedNotify\Services\Channels;

use App\Notifications\CustomerNotification;
use Notification;

/**
 * Email channel — reuses the EXACT pathway NotificationUtil::autoSendNotification
 * uses: the business email_settings are applied by CustomerNotification's
 * constructor (via NotificationUtil::configureEmail) and the mail is sent with
 * Notification::route('mail', $to)->notify(new CustomerNotification($data)).
 * We never touch mail config directly or build our own transport.
 *
 * Works for both users and contacts as long as an email address is resolvable.
 */
class EmailChannel implements ChannelContract
{
    public function send(array $message, array $recipient, array $context): array
    {
        try {
            $email = $recipient['email'] ?? null;
            if (empty($email)) {
                return ['status' => 'skipped', 'error' => 'no email address'];
            }

            $business = $context['business'] ?? null;

            $data = [
                'email_settings' => $business ? $business->email_settings : [],
                'subject'        => $message['subject'] ?? ($context['event_key'] ?? ''),
                'email_body'     => $message['body'] ?? '',
                'to_email'       => $email,
            ];

            Notification::route('mail', $email)->notify(new CustomerNotification($data));

            return ['status' => 'sent', 'error' => null];
        } catch (\Throwable $e) {
            \Log::warning('MedNotify EmailChannel failed: ' . $e->getMessage());

            return ['status' => 'failed', 'error' => $e->getMessage()];
        }
    }
}
