<?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 SMS messages via the Vonage SMS API (raw HTTP — no SDK).
 *
 * Notifications targeting this channel must implement `toVonageSms($notifiable)`
 * returning a string body (or `null` to skip).
 *
 * No-ops when VONAGE_KEY/SECRET are unset or when the notifiable user has no
 * phone number on `whatsapp_number` (the same verified column doubles as SMS
 * destination).
 */
final class VonageSmsChannel
{
    public const string NAME = 'vonage-sms';

    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.sms_from', 'FuelAlert');

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

            return;
        }

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

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

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

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

        $url = 'https://rest.nexmo.com/sms/json';

        try {
            $this->apiLogger->send(self::NAME, 'POST', $url, fn () => Http::timeout(10)
                ->asForm()
                ->post($url, [
                    'api_key' => $key,
                    'api_secret' => $secret,
                    'from' => $from,
                    'to' => ltrim($to, '+'),
                    'text' => $body,
                ]));
        } catch (Throwable $e) {
            Log::error('VonageSmsChannel: send failed', ['error' => $e->getMessage()]);
        }
    }
}
