<?php

namespace App\Services\WhatsApp;

use Illuminate\Support\Facades\Http;

/**
 * WhatsApp Cloud API (Meta official).
 *
 * Required config:
 *   - access_token       : Permanent or temp Bearer token from Meta App
 *   - phone_number_id    : The numeric ID of the registered business number
 *   - api_version        : optional, defaults to v18.0
 *
 * Reference:
 *   https://developers.facebook.com/docs/whatsapp/cloud-api/reference/messages
 *
 * Notes:
 *   - For unverified test apps, you can only send to whitelisted numbers.
 *   - Free tier: 1000 conversations/month after business verification.
 *   - Outside the 24-hour customer service window, only "template messages"
 *     (pre-approved templates) deliver. For NOC alerts that's fine because
 *     we send a template-shaped message.
 */
class WhatsAppCloudProvider extends WhatsAppProvider
{
    public function sendText(string $toPhone, string $body): array
    {
        $token = $this->config['access_token'] ?? null;
        $phoneId = $this->config['phone_number_id'] ?? null;
        $version = $this->config['api_version'] ?? 'v18.0';

        if (!$token || !$phoneId) {
            return ['ok' => false, 'error' => 'access_token and phone_number_id are required'];
        }

        $url = "https://graph.facebook.com/{$version}/{$phoneId}/messages";

        try {
            $resp = Http::withToken($token)
                ->timeout(15)
                ->retry(2, 500, throw: false)
                ->post($url, [
                    'messaging_product' => 'whatsapp',
                    'recipient_type' => 'individual',
                    'to' => $this->normalizePhone($toPhone),
                    'type' => 'text',
                    'text' => ['preview_url' => false, 'body' => $body],
                ]);

            if (!$resp->successful()) {
                return [
                    'ok' => false,
                    'error' => $resp->json('error.message') ?? "HTTP {$resp->status()}",
                    'response' => $resp->json(),
                ];
            }

            return [
                'ok' => true,
                'message_id' => $resp->json('messages.0.id'),
                'response' => $resp->json(),
            ];
        } catch (\Throwable $e) {
            return ['ok' => false, 'error' => $e->getMessage()];
        }
    }

    public function test(): array
    {
        $token = $this->config['access_token'] ?? null;
        $phoneId = $this->config['phone_number_id'] ?? null;
        $version = $this->config['api_version'] ?? 'v18.0';

        if (!$token || !$phoneId) {
            return ['ok' => false, 'error' => 'access_token and phone_number_id are required'];
        }

        // GET /{phone_number_id} — returns verified_name, status, etc.
        $resp = Http::withToken($token)->timeout(10)
            ->get("https://graph.facebook.com/{$version}/{$phoneId}");

        if (!$resp->successful()) {
            return ['ok' => false, 'error' => $resp->json('error.message') ?? "HTTP {$resp->status()}"];
        }

        return [
            'ok' => true,
            'message' => 'Connected as ' . ($resp->json('verified_name') ?: $resp->json('display_phone_number') ?: 'unknown'),
            'response' => $resp->json(),
        ];
    }
}
