<?php

namespace App\Services\Notification\Adapters;

use App\Models\NotificationDelivery;
use App\Services\Notification\Contracts\NotificationChannelAdapter;
use Illuminate\Support\Facades\Http;
use Illuminate\Validation\ValidationException;

class TelegramAdapter implements NotificationChannelAdapter
{
    public function send(NotificationDelivery $delivery): array
    {
        $token = data_get($delivery->channelConfig?->credentials, 'bot_token');
        if (! $token) {
            throw ValidationException::withMessages(['channel' => 'Bot token Telegram belum diatur.']);
        }
        $response = Http::timeout(30)->post("https://api.telegram.org/bot{$token}/sendMessage", [
            'chat_id' => $delivery->destination,
            'text' => $delivery->rendered_body,
            'parse_mode' => data_get($delivery->channelConfig?->settings, 'parse_mode'),
        ])->throw()->json();

        return ['provider_message_id' => (string) data_get($response, 'result.message_id'), 'response' => $response];
    }
}
