<?php

namespace App\Services\Messaging;

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

class CustomerSmsClient
{
    private ?string $lastError = null;

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

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

    /** @return array{ok: bool, data?: array<string, mixed>, error?: string, status?: int} */
    public function me(string $apiKey): array
    {
        return $this->get($apiKey, '/me');
    }

    /** @return array{ok: bool, data?: array<string, mixed>, error?: string, status?: int} */
    public function senders(string $apiKey): array
    {
        return $this->get($apiKey, '/senders');
    }

    public function send(string $apiKey, string $to, string $text, string $senderId): bool
    {
        $this->lastError = null;

        try {
            $res = Http::withToken($apiKey)->acceptJson()->timeout(30)
                ->post($this->base().'/send', [
                    'to' => $to,
                    'text' => $text,
                    'sender_id' => $senderId,
                ]);

            if ($res->status() === 402) {
                $this->lastError = (string) ($res->json('error') ?: 'Insufficient SMS credit. Top up your Ladill SMS wallet and try again.');

                return false;
            }

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

                return false;
            }

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

            return false;
        }
    }

    /** @return array{ok: bool, data?: array<string, mixed>, error?: string, status?: int} */
    private function get(string $apiKey, string $path): array
    {
        try {
            $res = Http::withToken($apiKey)->acceptJson()->timeout(15)
                ->get($this->base().$path);

            if ($res->status() === 401) {
                return ['ok' => false, 'error' => 'Invalid SMS API key.', 'status' => 401];
            }

            if ($res->failed()) {
                return [
                    'ok' => false,
                    'error' => (string) ($res->json('error') ?: 'Could not validate SMS credentials.'),
                    'status' => $res->status(),
                ];
            }

            return ['ok' => true, 'data' => $res->json() ?? [], 'status' => $res->status()];
        } catch (\Throwable $e) {
            Log::warning('Customer SMS meta request failed', ['path' => $path, 'error' => $e->getMessage()]);

            return ['ok' => false, 'error' => 'Could not reach Ladill SMS. Please try again.'];
        }
    }
}
