<?php

namespace App\Sms\Service;

use App\Sms\Entity\SmsLog;
use App\Sms\Message\SendSmsMessage;
use App\Sms\Provider\KavehNegarProvider;
use App\Sms\Provider\RanginehProvider;
use App\Sms\Provider\SmsProviderInterface;
use App\Sms\Repository\SmsLogRepository;
use Symfony\Component\Messenger\MessageBusInterface;

class SmsService
{
    private array $providers;

    public function __construct(
        private readonly KavehNegarProvider  $kavenegar,
        private readonly RanginehProvider    $rangineh,
        private readonly SmsLogRepository    $logRepo,
        private readonly MessageBusInterface $bus,
    ) {
        $this->providers = [
            'kavenegar' => $kavenegar,
            'rangineh'  => $rangineh,
        ];
    }

    public function dispatchAsync(
        string $mobile,
        string $message,
        string $provider = 'kavenegar',
        ?string $templateUuid = null,
        array $templateVars = [],
        ?string $templateCode = null,
        string $tag = SmsLog::TAG_GLOBAL,
    ): void {
        $this->bus->dispatch(new SendSmsMessage(
            $mobile, $message, $provider, $templateUuid, $templateVars, $templateCode, $tag
        ));
    }

    public function sendNow(SendSmsMessage $msg): bool
    {
        $provider = $this->resolveProvider($msg->provider);

        $success = ($msg->templateCode !== null)
            ? $provider->sendTemplate($msg->mobile, $msg->templateCode, $msg->templateVars)
            : $provider->send($msg->mobile, $msg->message);

        $log = new SmsLog($msg->mobile, $msg->message, $provider->getName(), $success, $msg->tag);
        if ($msg->templateUuid) $log->setTemplateUuid($msg->templateUuid);
        $this->logRepo->save($log);

        return $success;
    }

    private function resolveProvider(string $name): SmsProviderInterface
    {
        return $this->providers[$name] ?? $this->kavenegar;
    }
}
