<?php

namespace App\Services\Notification;

use App\Services\Notification\Exceptions\NotificationServerNotRespondingException;
use App\Services\Notification\Exceptions\OperatorNotConnectedException;
use App\Services\Notification\Exceptions\OperatorOfflineException;
use Illuminate\Http\Client\ConnectionException;
use Illuminate\Http\Client\RequestException;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;

class NotificationService
{
    public function deliverDataToNotificationServer(array $data): void
    {
        try
        {
            $response = Http::retry(3)
                ->post(config('globalVariables.NOTIFICATION_SERVER_URL'), $data)
                ->throwIfServerError();

            $response_status = json_decode($response->body())->status;

            throw_if($response_status == 1,
                new OperatorOfflineException(__('messages.the_operator_is_offline'))
            );

            throw_if($response_status == 2,
                new OperatorNotConnectedException(__('messages.operator_could_not_connect'))
            );
        }
        catch (RequestException $exception)
        {
            Log::channel('notification_service')
                ->error(RequestException::class, [
                    $exception->getMessage(),
                    NotificationServerNotRespondingException::class,
                    __('messages.notification_server_is_down')
            ]);

            throw_if($exception->response->serverError(),
                new NotificationServerNotRespondingException(__('messages.notification_server_is_down'))
            );
        }
    }
}
