<?php

namespace App\Services\WhatsApp;

use Illuminate\Support\Facades\Http;

/**
 * Twilio WhatsApp.
 *
 * Required config:
 *   - account_sid : Twilio Account SID
 *   - auth_token  : Twilio Auth Token
 *   - from_number : your WhatsApp-enabled Twilio number, format "+14155238886"
 *                   (sandbox uses the shared number with a join keyword)
 *
 * Reference:
 *   https://www.twilio.com/docs/whatsapp/api
 *
 * Sandbox vs production:
 *   - Sandbox: instant. Recipients must first text "join <keyword>" to your
 *     Twilio sandbox number. Useful for dev.
 *   - Production: requires WhatsApp Sender registration + Meta business
 *     verification. Same Twilio account, different from_number.
 */
class WhatsAppTwilioProvider extends WhatsAppProvider
{
    public function sendText(string $toPhone, string $body): array
    {
        $sid = $this->config['account_sid'] ?? null;
        $token = $this->config['auth_token'] ?? null;
        $from = $this->config['from_number'] ?? null;

        if (!$sid || !$token || !$from) {
            return ['ok' => false, 'error' => 'account_sid, auth_token, and from_number are required'];
        }

        $url = "https://api.twilio.com/2010-04-01/Accounts/{$sid}/Messages.json";

        try {
            $resp = Http::withBasicAuth($sid, $token)
                ->timeout(15)
                ->retry(2, 500, throw: false)
                ->asForm()
                ->post($url, [
                    'From' => 'whatsapp:' . $this->normalizeForTwilio($from),
                    'To' => 'whatsapp:' . $this->normalizeForTwilio($toPhone),
                    'Body' => $body,
                ]);

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

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

    public function test(): array
    {
        $sid = $this->config['account_sid'] ?? null;
        $token = $this->config['auth_token'] ?? null;

        if (!$sid || !$token) {
            return ['ok' => false, 'error' => 'account_sid and auth_token are required'];
        }

        // Hit the account info endpoint to verify credentials.
        $resp = Http::withBasicAuth($sid, $token)->timeout(10)
            ->get("https://api.twilio.com/2010-04-01/Accounts/{$sid}.json");

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

        return [
            'ok' => true,
            'message' => 'Connected: ' . ($resp->json('friendly_name') ?: $sid),
            'response' => ['status' => $resp->json('status')],
        ];
    }

    /**
     * Twilio expects E.164 *with* leading +. Our base normaliser strips it.
     */
    private function normalizeForTwilio(string $phone): string
    {
        $clean = $this->normalizePhone($phone);
        return '+' . $clean;
    }
}
