<?php

declare(strict_types=1);

namespace SmsNotifier\Facade;

use SmsNotifier\Data\NotificationData;
use SmsNotifier\Data\PluginData;
use SmsNotifier\Factory\MessageTextFactory;
use SmsNotifier\Service\Logger;
use SmsNotifier\Service\OptionsManager;
use SmsNotifier\Service\SmsNumberProvider;
use Twilio\Rest\Client;

class TwilioNotifierFacade extends AbstractMessageNotifierFacade
{
    private $twilioClient;
    private $pluginData;

    public function __construct(
        Logger $logger,
        MessageTextFactory $messageTextFactory,
        SmsNumberProvider $smsNumberProvider,
        OptionsManager $optionsManager
    ) {
        parent::__construct($logger, $messageTextFactory, $smsNumberProvider);
        $this->pluginData = $optionsManager->load();
    }

    public function getTwilioClient(): Client
    {
        if (!$this->twilioClient) {
            $this->twilioClient = new Client(
                $this->pluginData->twilioAccountSid ?? '',
                $this->pluginData->twilioAuthToken ?? ''
            );
        }
        return $this->twilioClient;
    }

    protected function sendWhatsApp(NotificationData $notificationData, string $clientSmsNumber): void
    {
        $this->logger->info("TwilioNotifierFacade: Enviando WhatsApp a $clientSmsNumber (Mock)");
    }

    protected function sendMessage(
        NotificationData $notificationData,
        string $clientSmsNumber,
        string $messageBody
    ): void {
        try {
            $message = $this->getTwilioClient()->messages->create(
                $clientSmsNumber,
                [
                    'from' => $this->pluginData->twilioSmsNumber ?? '',
                    'body' => $messageBody,
                ]
            );
            $this->logger->info(sprintf('Twilio status: %s, ID: %s', $message->status, $message->sid));
        } catch (\Exception $e) {
            $this->logger->error("Error en Twilio: " . $e->getMessage());
        }
    }
}
