<?php declare(strict_types=1);

namespace apexl\Io\modules\notifierTwilio\drivers;

use apexl\Config\Singleton as Config;
use apexl\Io\modules\notifier\exceptions\notifierException;
use apexl\Io\modules\notifier\interfaces\smsNotifierDriverInterface;
use apexl\Io\modules\notifierTwilio\dto\TwilioConfigDto;
use Exception;
use Twilio\Exceptions\TwilioException;
use Twilio\Rest\Client;

class twilioSmsNotifierDriver implements smsNotifierDriverInterface
{
    private Client $client;
    private TwilioConfigDto $config;

    /**
     * @throws notifierException
     */
    public function __construct()
    {
        try {
            $this->config = TwilioConfigDto::fromConfig();

            $this->client = new Client(
                $this->config->sid,
                $this->config->token,
            );
        } catch (Exception $e) {
            $this->throwException($e);
        }
    }

    /**
     * @throws notifierException
     */
    public function send(string $to, string $body): void
    {
        try {
            $this->client->messages->create(
                $to,
                [
                    'from' => $this->config->from,
                    'body' => $body,
            ]);
        } catch (TwilioException $e) {
            $this->throwException($e);
        }
    }

    /**
     * @throws notifierException
     */
    private function throwException(Exception $e): void
    {
        throw new notifierException(
            sprintf('Could not send via Twilio: %s', $e->getMessage()),
            $e->getCode(),
            $e
        );
    }
}
