<?php

namespace App\Services\Notifications;

use App\Models\Business;
use App\Support\PhoneNumber;
use Illuminate\Support\Facades\Http;
use Throwable;

class NextSmsService
{
    public function send(Business $business, string $recipient, string $message): NotificationDeliveryResult
    {
        $apiKey=trim((string)$business->nextsms_api_key);
        $senderId=trim((string)$business->nextsms_sender_id);

        if($apiKey==='' || $senderId==='') {
            return NotificationDeliveryResult::failed('NextSMS API key and Sender ID are not configured.');
        }

        $to=$this->normalizeRecipient($recipient, $business->phone_country_code);
        if($to===null) {
            return NotificationDeliveryResult::failed('The SMS recipient phone number is invalid.');
        }

        $endpoint=(string)config('reminders.providers.nextsms.endpoint','https://messaging-service.co.tz/api/sms/v1/text/single');
        $timeout=max(1,(int)config('reminders.providers.nextsms.timeout',15));

        try {
            $response=Http::acceptJson()
                ->asJson()
                ->timeout($timeout)
                ->withHeaders(['Authorization'=>'Basic '.$apiKey])
                ->post($endpoint,[
                    'from'=>$senderId,
                    'to'=>$to,
                    'text'=>$message,
                ]);

            $body=mb_substr((string)$response->body(),0,12000);
            if(!$response->successful()) {
                return NotificationDeliveryResult::failed('NextSMS returned HTTP '.$response->status().'.',$body);
            }

            return NotificationDeliveryResult::delivered($body!=='' ? $body : json_encode(['status'=>$response->status()]));
        } catch(Throwable $e) {
            return NotificationDeliveryResult::failed($e->getMessage());
        }
    }

    public function normalizeRecipient(string $recipient, ?string $countryCode = null): ?string
    {
        return PhoneNumber::normalize($recipient, $countryCode);
    }
}
