<?php

namespace Modules\Auth\Services;

use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
use Modules\Auth\Contracts\SmsSender;
use RuntimeException;

class OneWaySmsSender implements SmsSender
{
    public function send(string $phoneNumber, string $message): void
    {
        $baseUrl = (string) config('onewaysms.base_url');
        $username = (string) config('onewaysms.api_username');
        $password = (string) config('onewaysms.api_password');
        $senderId = (string) config('onewaysms.sender_id');

        if ($baseUrl === '' || $username === '' || $password === '' || $senderId === '') {
            throw new RuntimeException('OneWaySMS credentials are not configured.');
        }

        $mobileNo = $this->toInternationalMobileNumber($phoneNumber);

        $response = Http::timeout((int) config('http.timeout', 30))
            ->connectTimeout((int) config('http.connect_timeout', 10))
            ->get($baseUrl, [
                'apiusername' => $username,
                'apipassword' => $password,
                'senderid' => $senderId,
                'mobileno' => $mobileNo,
                'message' => $message,
                'languagetype' => 1,
            ]);

        if (! $response->successful()) {
            Log::error('OneWaySMS HTTP request failed', [
                'status' => $response->status(),
                'body' => $response->body(),
                'phone_number' => $mobileNo,
            ]);

            throw new RuntimeException('Failed to send SMS via OneWaySMS.');
        }

        $mtId = trim($response->body());

        // Positive MT ID = success; zero/negative = gateway error codes.
        if (! is_numeric($mtId) || (int) $mtId <= 0) {
            Log::error('OneWaySMS gateway rejected SMS', [
                'mt_id' => $mtId,
                'phone_number' => $mobileNo,
            ]);

            throw new RuntimeException('OneWaySMS gateway rejected the SMS request.');
        }

        Log::info('OneWaySMS sent successfully', [
            'mt_id' => $mtId,
            'phone_number' => $mobileNo,
        ]);
    }

    protected function toInternationalMobileNumber(string $phoneNumber): string
    {
        $phoneNumber = preg_replace('/[\s\-]/', '', trim($phoneNumber)) ?? '';

        if (str_starts_with($phoneNumber, '+')) {
            $phoneNumber = substr($phoneNumber, 1);
        }

        if (str_starts_with($phoneNumber, '0')) {
            $phoneNumber = '60'.substr($phoneNumber, 1);
        }

        return $phoneNumber;
    }
}
