<?php

namespace App\Notify\Channels;

use App\Notify\Contracts\Channel;
use App\Notify\Message;
use Illuminate\Support\Facades\Http;

/**
 * WhatsApp Cloud API (Meta direct). Free tier: 1000 service conversations
 * per month. Setup:
 *   1. developers.facebook.com → My Apps → Create App → Business
 *   2. Add WhatsApp product → grab phone_number_id + permanent access token
 *   3. Verify recipients (or send approved templates to unverified numbers)
 *   4. notify:add-channel whatsapp_cloud phone_number_id=... access_token=... to=8801...
 */
class WhatsAppCloudChannel implements Channel
{
    public function key(): string { return 'whatsapp_cloud'; }

    public function requiredConfig(): array { return ['phone_number_id', 'access_token', 'to']; }

    public function send(array $config, Message $message): array
    {
        $body = "*[" . strtoupper($message->severity) . "] {$message->title}*\n\n{$message->body}";
        if ($message->url) $body .= "\n\n{$message->url}";

        $payload = [
            'messaging_product' => 'whatsapp',
            'to'                => $config['to'],
            'type'              => 'text',
            'text'              => ['body' => substr($body, 0, 4096)],
        ];

        try {
            $resp = Http::timeout(10)
                ->withToken($config['access_token'])
                ->post(
                    "https://graph.facebook.com/v17.0/{$config['phone_number_id']}/messages",
                    $payload
                );
            if (! $resp->successful()) {
                return ['ok' => false, 'error' => 'Meta HTTP ' . $resp->status() . ': ' . substr($resp->body(), 0, 200)];
            }
            return ['ok' => true, 'response' => $resp->json()];
        } catch (\Throwable $e) {
            return ['ok' => false, 'error' => $e->getMessage()];
        }
    }
}
