<?php

namespace App\Services\Billing;

use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Str;

/**
 * Platform suite SMS (zero-config): channel=suite, no customer SMS API key.
 */
class PlatformSmsClient
{
    private ?string $lastError = null;

    public function lastError(): ?string
    {
        return $this->lastError;
    }

    private function base(): string
    {
        return rtrim((string) config('sms.platform_api_url', 'https://ladill.com/api'), '/');
    }

    private function token(): string
    {
        return (string) config('sms.platform_api_key', '');
    }

    public function isConfigured(): bool
    {
        return $this->token() !== '';
    }

    public function send(
        string $ownerPublicId,
        string $to,
        string $message,
        ?string $senderId = null,
        ?string $idempotencyKey = null,
    ): bool {
        $this->lastError = null;

        if (! $this->isConfigured()) {
            $this->lastError = 'SMS is not configured on this Care instance. Set SMS_API_KEY_CARE.';

            return false;
        }

        $key = $idempotencyKey ?: ('care-sms-'.Str::uuid());

        try {
            $res = Http::withToken($this->token())
                ->withHeaders(['Idempotency-Key' => $key])
                ->acceptJson()
                ->timeout(30)
                ->post($this->base().'/sms/messages/send', array_filter([
                    'user' => $ownerPublicId,
                    'channel' => 'suite',
                    'to' => $to,
                    'text' => $message,
                    'sender_id' => $senderId ?? config('sms.default_sender_id'),
                    'reference' => $key,
                ], static fn ($v) => $v !== null && $v !== ''));

            if ($res->status() === 402) {
                $this->lastError = (string) ($res->json('error') ?: 'SMS allowance exceeded. Upgrade Care Pro or top up your wallet.');
                Log::warning('Care suite SMS: allowance/balance', ['user' => $ownerPublicId]);

                return false;
            }

            if ($res->failed()) {
                $this->lastError = (string) ($res->json('error') ?: $res->json('message') ?: 'The SMS could not be sent.');
                Log::warning('Care suite SMS failed', ['status' => $res->status(), 'body' => $res->body()]);

                return false;
            }

            return (bool) ($res->json('success') ?? true);
        } catch (\Throwable $e) {
            $this->lastError = 'Could not reach the SMS service. Please try again.';
            Log::warning('Care suite SMS error', ['error' => $e->getMessage()]);

            return false;
        }
    }
}
