<?php

namespace App\Services\Messaging;

use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;

class Fast2SmsService
{
    public function sendMessage(string $mobile, string $message): bool
    {
        $apiUrl = (string) config('lead.fast2sms.api_base_url');
        $payload = [
            'route' => (string) config('lead.fast2sms.route', 'dlt'),
            'sender_id' => (string) config('lead.fast2sms.sender_id'),
            'entity_id' => (string) config('lead.fast2sms.entity_id'),
            'message' => $message,
            'numbers' => $mobile,
        ];

        Log::info('Fast2SMS request prepared.', [
            'url' => $apiUrl,
            'mobile' => $this->maskMobile($mobile),
            'payload' => $this->sanitizePayload($payload),
        ]);

        if (! config('lead.fast2sms.enabled')) {
            Log::info('Fast2SMS disabled, skipping SMS.', ['mobile' => $mobile]);
            return false;
        }

        $apiKey = (string) config('lead.fast2sms.api_key');
        $entityId = (string) config('lead.fast2sms.entity_id');
        if ($apiKey === '') {
            Log::warning('Fast2SMS API key missing.');
            return false;
        }
        if ($apiUrl === '') {
            Log::warning('Fast2SMS API URL missing.');
            return false;
        }
        if ($entityId === '') {
            Log::warning('Fast2SMS Entity ID missing.');
            return false;
        }

        try {
            $response = Http::withOptions([
                'verify' => false,
            ])->withHeaders([
                'authorization' => $apiKey,
                'accept' => 'application/json',
                'content-type' => 'application/json',
            ])->post($apiUrl, $payload);

            if (! $response->successful()) {
                Log::error('Fast2SMS request failed.', [
                    'status' => $response->status(),
                    'body' => $response->body(),
                    'mobile' => $this->maskMobile($mobile),
                    'url' => $apiUrl,
                    'payload' => $this->sanitizePayload($payload),
                ]);
                return false;
            }

            Log::info('Fast2SMS request succeeded.', [
                'status' => $response->status(),
                'body' => $response->body(),
                'mobile' => $this->maskMobile($mobile),
            ]);

            return true;
        } catch (\Throwable $exception) {
            report($exception);
            return false;
        }
    }

    public function sendOtp(string $mobile, string $otp): bool
    {
        $template = (string) config('lead.fast2sms.otp_template');
        $message = str_replace('{{otp}}', $otp, $template);

        return $this->sendMessage($mobile, $message);
    }

    private function maskMobile(string $mobile): string
    {
        if (strlen($mobile) <= 4) {
            return str_repeat('*', strlen($mobile));
        }
        return str_repeat('*', max(strlen($mobile) - 4, 0)) . substr($mobile, -4);
    }

    private function sanitizePayload(array $payload): array
    {
        $payload['numbers'] = $this->maskMobile((string) ($payload['numbers'] ?? ''));
        $payload['message'] = strlen((string) ($payload['message'] ?? '')) > 80 ? substr((string) $payload['message'], 0, 80) . '...' : $payload['message'];
        return $payload;
    }
}
