<?php

namespace App\Notifications\Channels;

use App\Services\ApiLogger;
use Illuminate\Notifications\Notification;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
use Throwable;

/**
 * Sends WhatsApp messages via the Vonage Messages API (raw HTTP — no SDK).
 *
 * Notifications targeting this channel must implement `toVonageWhatsApp($notifiable)`
 * returning a string body (or `null` to skip).
 *
 * No-ops when VONAGE_KEY/SECRET/whatsapp_from are unset, when the user is not
 * verified (no whatsapp_verified_at), when whatsapp_number is missing, or when
 * the notification returns null.
 */
final class VonageWhatsAppChannel
{
    public const string NAME = 'vonage-whatsapp';

    public function __construct(
        private readonly ApiLogger $apiLogger,
    ) {}

    public function send(mixed $notifiable, Notification $notification): void
    {
        $key = config('services.vonage.key');
        $secret = config('services.vonage.secret');
        $from = config('services.vonage.whatsapp_from');

        if ($key === null || $secret === null || $from === null) {
            Log::info('VonageWhatsAppChannel: skipped — credentials not configured');

            return;
        }

        $to = $notifiable->whatsapp_number ?? null;
        $verified = $notifiable->whatsapp_verified_at ?? null;

        if ($to === null || $verified === null) {
            return;
        }

        $body = method_exists($notification, 'toVonageWhatsApp')
            ? $notification->toVonageWhatsApp($notifiable)
            : null;

        if ($body === null) {
            return;
        }

        $url = 'https://api.nexmo.com/v1/messages';

        try {
            $this->apiLogger->send(self::NAME, 'POST', $url, fn () => Http::timeout(10)
                ->withBasicAuth($key, $secret)
                ->acceptJson()
                ->post($url, [
                    'message_type' => 'text',
                    'channel' => 'whatsapp',
                    'from' => $from,
                    'to' => $to,
                    'text' => $body,
                ]));
        } catch (Throwable $e) {
            Log::error('VonageWhatsAppChannel: send failed', ['error' => $e->getMessage()]);
        }
    }
}
