<?php

namespace App\Services;

use App\Models\Business;
use App\Support\PhoneNumber;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Str;
use RuntimeException;

class WhatsAppGatewayService
{
    /** @return array{successful:bool,status:?int,response:string,recipient:string,message_id:?string} */
    public function sendText(Business $business, string $recipient, string $message): array
    {
        $endpoint = trim((string) $business->whatsapp_api_endpoint);
        $token = trim((string) $business->whatsapp_api_token);
        if ($endpoint === '' || $token === '') {
            throw new RuntimeException('WhatsApp Cloud API endpoint and token must be configured before reports can be sent.');
        }

        $normalized = PhoneNumber::normalize($recipient, $business->phone_country_code);
        if ($normalized === null) {
            throw new RuntimeException('The WhatsApp recipient phone number is invalid.');
        }

        $response = Http::acceptJson()
            ->asJson()
            ->withToken($token)
            ->timeout(20)
            ->post($endpoint, [
                'messaging_product' => 'whatsapp',
                'to' => $normalized,
                'type' => 'text',
                'text' => [
                    'preview_url' => false,
                    'body' => Str::limit($message, 4000, '…'),
                ],
            ]);

        $body = Str::limit(trim($response->body()), 4000, '…');

        return [
            'successful' => $response->successful(),
            'status' => $response->status(),
            'response' => $body,
            'recipient' => $normalized,
            'message_id' => data_get($response->json(), 'messages.0.id'),
        ];
    }
}
