<?php

namespace App\Modules\Sms\Infobip;

use App\Core\Sms\AbstractSms;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;

class Infobip extends AbstractSms
{
    public function sendSms(array $params): array
    {
        $to = $params['to'] ?? null;
        $content = $params['content'] ?? null;
        if (! $to || ! $content) {
            return ['success' => false, 'error' => 'Required fields missing (to, content)'];
        }
        if ($this->isTestMode) {
            Log::info('Infobip TEST SMS', ['to' => $to, 'content' => $content]);

            return ['success' => true, 'message_id' => 'test_ib_'.uniqid()];
        }
        $apiKey = $this->getConfig('api_key');
        $baseUrl = rtrim((string) $this->getConfig('base_url', 'https://api.infobip.com'), '/');
        $from = $this->getConfig('from');
        if (! $apiKey || ! $from) {
            return ['success' => false, 'error' => 'Infobip configuration incomplete'];
        }
        $defaultDialCode = $this->getConfig('default_country_code'); // global provider: config'ten, uydurma yok
        try {
            $resp = Http::withHeaders([
                'Authorization' => "App {$apiKey}",
                'Accept' => 'application/json',
                'Content-Type' => 'application/json',
            ])->timeout(30)->post("{$baseUrl}/sms/2/text/advanced", [
                'messages' => [[
                    'from' => $from,
                    'destinations' => [['to' => $this->normalizeMsisdn($to, $defaultDialCode)]],
                    'text' => $content,
                ]],
            ]);
            // HTTP hatası: ham gövde loglanmaz/döndürülmez (creds/PII sızıntısı riski).
            if (! $resp->successful()) {
                return ['success' => false, 'error' => 'Infobip HTTP '.$resp->status()];
            }
            $data = $resp->json();
            $msg = $data['messages'][0] ?? null;

            // false-success guard: HTTP 200 dönse bile per-mesaj statüsü REJECTED/UNDELIVERABLE olabilir.
            // Başarıyı gövde-statüsü (status.groupName) ile gate et.
            $groupName = strtoupper((string) ($msg['status']['groupName'] ?? ''));
            $accepted = ['PENDING', 'DELIVERED'];
            if (! in_array($groupName, $accepted, true)) {
                $detail = $msg['status']['name'] ?? ($msg['status']['description'] ?? $groupName);

                return ['success' => false, 'error' => 'Infobip message rejected: '.($detail ?: 'unknown status')];
            }

            $messageId = $msg['messageId'] ?? null;
            if (! $messageId) {
                // message_id yoksa UYDURMA — belirsiz sonuç, success:false.
                return ['success' => false, 'error' => 'Infobip response missing messageId'];
            }

            return ['success' => true, 'message_id' => $messageId];
        } catch (\Throwable $e) {
            return ['success' => false, 'error' => $e->getMessage()];
        }
    }

    public function testConnection(array $params): array
    {
        $apiKey = $params['api_key'] ?? $this->getConfig('api_key');
        $baseUrl = rtrim((string) ($params['base_url'] ?? $this->getConfig('base_url', 'https://api.infobip.com')), '/');
        if (! $apiKey) {
            return ['success' => false, 'message' => 'api_key required'];
        }
        $resp = Http::withHeaders(['Authorization' => "App {$apiKey}"])->timeout(15)
            ->get("{$baseUrl}/account/1/balance");

        return $resp->successful()
            ? ['success' => true, 'message' => 'Infobip connection OK']
            : ['success' => false, 'message' => 'Infobip HTTP '.$resp->status()];
    }

    public function getRequiredConfigFields(): array
    {
        return ['api_key', 'from'];
    }

    public function getConfigFields(): array
    {
        return [
            'api_key' => ['type' => 'password', 'label' => 'Infobip API Key', 'required' => true, 'encrypted' => true],
            'base_url' => ['type' => 'text', 'label' => 'Base URL', 'default' => 'https://api.infobip.com'],
            'from' => ['type' => 'text', 'label' => 'Sender Name / Number', 'required' => true],
            'default_country_code' => ['type' => 'text', 'label' => 'Default Country Code (e.g. 90, 1)', 'required' => false],
            'test_mode' => ['type' => 'boolean', 'label' => 'Test Mode', 'default' => true],
        ];
    }
}
