<?php

namespace App\Domain\WhatsApp\Drivers;

use App\Domain\WhatsApp\Contracts\WhatsAppDriver;
use App\Domain\WhatsApp\SendResult;
use App\Models\WaMessage;
use Illuminate\Support\Facades\Http;

/** WhatsApp Cloud API (Meta) driver. */
class MetaDriver implements WhatsAppDriver
{
    public function sendText(WaMessage $message): SendResult
    {
        return $this->post([
            'messaging_product' => 'whatsapp',
            'recipient_type' => 'individual',
            'to' => $message->to_phone,
            'type' => 'text',
            'text' => ['preview_url' => true, 'body' => $message->body],
        ]);
    }

    public function sendDocument(WaMessage $message, string $mediaUrl): SendResult
    {
        return $this->post([
            'messaging_product' => 'whatsapp',
            'to' => $message->to_phone,
            'type' => 'document',
            'document' => [
                'link' => $mediaUrl,
                'filename' => $message->media_filename ?? 'document.pdf',
                'caption' => $message->body,
            ],
        ]);
    }

    protected function post(array $payload): SendResult
    {
        $cfg = config('whatsapp.meta');
        $url = sprintf('https://graph.facebook.com/%s/%s/messages', $cfg['api_version'], $cfg['phone_number_id']);

        try {
            $res = Http::withToken($cfg['token'])->asJson()->timeout(20)->post($url, $payload);
        } catch (\Throwable $e) {
            return SendResult::failure('network', $e->getMessage(), retryable: true);
        }

        if ($res->successful()) {
            return SendResult::success($res->json('messages.0.id', 'meta_unknown'));
        }

        $code = (string) $res->json('error.code', $res->status());
        $reason = $res->json('error.message', 'Unknown error');
        // 4xx (except 429) are permanent; 429/5xx are retryable.
        $retryable = $res->status() === 429 || $res->status() >= 500;

        return SendResult::failure($code, $reason, $retryable);
    }
}
