<?php

namespace App\Services\Notifications;

use Illuminate\Http\Client\ConnectionException;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;

/**
 * Generic HTTP SMS gateway.
 *
 * Ugandan aggregators (Africa's Talking, EgoSMS, Yo! Uganda and friends) all
 * expose a similar "POST recipients + message" endpoint, so the field names
 * are config-driven. Set `services.sms.*` to match the contracted provider.
 */
class HttpSmsProvider implements SmsServiceInterface
{
    public function name(): string
    {
        return 'http';
    }

    public function send(string $to, string $message): bool
    {
        return $this->dispatch([$this->normalise($to)], $message) > 0;
    }

    public function sendBulk(array $recipients, string $message): int
    {
        $numbers = array_values(array_filter(array_map($this->normalise(...), $recipients)));

        return $numbers === [] ? 0 : $this->dispatch($numbers, $message);
    }

    protected function dispatch(array $numbers, string $message): int
    {
        $config = $this->config();

        if (blank($config['endpoint']) || blank($config['api_key'])) {
            Log::warning('SMS not sent: provider is not configured.', ['recipients' => count($numbers)]);

            return 0;
        }

        try {
            $response = Http::timeout(15)
                ->withHeaders([$config['auth_header'] => $config['api_key']])
                ->acceptJson()
                ->asForm()
                ->post($config['endpoint'], [
                    $config['recipient_field'] => implode(',', $numbers),
                    $config['message_field'] => $message,
                    $config['sender_field'] => config('kcu.sms.sender_id'),
                ]);
        } catch (ConnectionException $e) {
            Log::error('SMS gateway unreachable', ['error' => $e->getMessage()]);

            return 0;
        }

        if ($response->failed()) {
            Log::error('SMS gateway rejected request', [
                'status' => $response->status(),
                'body' => $response->body(),
            ]);

            return 0;
        }

        return count($numbers);
    }

    /** Normalise local Ugandan numbers to E.164 (+256...). */
    protected function normalise(string $number): ?string
    {
        $digits = preg_replace('/[^0-9+]/', '', $number);

        if (blank($digits)) {
            return null;
        }

        if (str_starts_with($digits, '+')) {
            return $digits;
        }

        if (str_starts_with($digits, '0')) {
            return '+256'.substr($digits, 1);
        }

        if (str_starts_with($digits, '256')) {
            return '+'.$digits;
        }

        return '+'.$digits;
    }

    protected function config(): array
    {
        return array_merge([
            'endpoint' => null,
            'api_key' => config('kcu.sms.api_key'),
            'auth_header' => 'Authorization',
            'recipient_field' => 'to',
            'message_field' => 'message',
            'sender_field' => 'from',
        ], (array) config('services.sms', []));
    }
}
