<?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;

/** Twilio WhatsApp driver. */
class TwilioDriver implements WhatsAppDriver
{
    public function sendText(WaMessage $message): SendResult
    {
        return $this->post([
            'From' => config('whatsapp.twilio.from'),
            'To' => 'whatsapp:+'.ltrim($message->to_phone, '+'),
            'Body' => $message->body,
        ]);
    }

    public function sendDocument(WaMessage $message, string $mediaUrl): SendResult
    {
        return $this->post([
            'From' => config('whatsapp.twilio.from'),
            'To' => 'whatsapp:+'.ltrim($message->to_phone, '+'),
            'Body' => $message->body,
            'MediaUrl' => $mediaUrl,
        ]);
    }

    protected function post(array $form): SendResult
    {
        $cfg = config('whatsapp.twilio');
        $url = "https://api.twilio.com/2010-04-01/Accounts/{$cfg['sid']}/Messages.json";

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

        if ($res->successful()) {
            return SendResult::success($res->json('sid', 'twilio_unknown'));
        }

        $code = (string) $res->json('code', $res->status());
        $reason = $res->json('message', 'Unknown error');
        $retryable = $res->status() === 429 || $res->status() >= 500;

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