<?php

namespace Modules\MedNotify\Services\Channels;

use App\Utils\ModuleUtil;

/**
 * WhatsApp channel — delegates to the WhatsApp module's WaSender (its single
 * public entry point) ONLY when that module is installed for this host. When it
 * is absent the send is a soft no-op (status=skipped), so MedNotify never hard-
 * depends on WhatsApp. WaSender itself persists + throttles + dedupes the send.
 */
class WhatsAppChannel implements ChannelContract
{
    public function send(array $message, array $recipient, array $context): array
    {
        try {
            if (! (new ModuleUtil())->isModuleInstalled('WhatsApp')) {
                return ['status' => 'skipped', 'error' => 'WhatsApp module not installed'];
            }

            $mobile = $recipient['mobile'] ?? null;
            if (empty($mobile)) {
                return ['status' => 'skipped', 'error' => 'no mobile number'];
            }

            $senderClass = \Modules\WhatsApp\Entities\Services\WaSender::class;
            if (! class_exists($senderClass)) {
                return ['status' => 'skipped', 'error' => 'WaSender unavailable'];
            }

            $businessId = (int) ($context['business_id'] ?? 0);

            $sender = new $senderClass();
            $result = $sender->send([
                'business_id' => $businessId,
                'to'          => $mobile,
                'body'        => $message['body'] ?? '',
                'source'      => 'mednotify:' . ($context['event_key'] ?? 'event'),
                'dedupe_key'  => $context['dedupe_key'] ?? null,
            ]);

            // WaSender returns null when WhatsApp is disabled for the business or
            // the contact opted out — that's a soft skip, not a failure.
            if ($result === null) {
                return ['status' => 'skipped', 'error' => 'WhatsApp disabled or recipient opted out'];
            }

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

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