<?php declare(strict_types=1);

namespace Apexl\Io\NotifierTwilio\Drivers;

use apexl\Io\modules\notifier\exceptions\notifierException;
use apexl\Io\modules\notifier\interfaces\smsNotifierDriverInterface;
use Apexl\Io\NotifierTwilio\Dtos\TwilioConfigDto;
use Exception;
use Twilio\Exceptions\TwilioException;
use Twilio\Rest\Client;

final readonly class TwilioSmsNotifierDriver implements smsNotifierDriverInterface
{
    public function __construct(
        private TwilioConfigDto $config,
        private Client $client,
    ) {}

    /**
     * @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
        );
    }
}
