<?php

namespace Plugins\Sms;

use Plugins\Sms\Contracts\PatternSmsDriverInterface;
use Plugins\Sms\Contracts\Response;
use Plugins\Sms\Contracts\SmsDriverInterface;
use Plugins\Sms\Exceptions\SmsDriverNotFoundException;
use Plugins\Sms\Exceptions\SmsDriverNotSupportPatternException;

class SmsBuilder
{
    private array $to;
    private string $text;
    private string $driverName;
    private SmsDriverInterface $driver;
    private array $configs;
    private string $patternName = '';

    public function __construct()
    {
        $this->configs = config('sms');
    }

    public function to(array $to): self
    {
        $this->to = $to;
        return $this;
    }

    public function text(string $text): self
    {
        $this->text = $text;
        return $this;
    }

    /**
     * @throws SmsDriverNotFoundException
     */
    public function via(string $driver): self
    {
        if ($this->configs['map'][$driver] ?? false) {
            $this->driverName = $driver;
            $this->driver = new $this->configs['map'][$driver]();
            return $this;
        }

        throw new SmsDriverNotFoundException("Driver $driver not found");
    }

    public function data(array $data): self
    {
        $this->driver->setData($data);
        return $this;
    }

    /**
     * @throws SmsDriverNotSupportPatternException
     */
    public function send(): Response
    {
        if ($this->patternName) {
            if (!$this->driver instanceof PatternSmsDriverInterface) {
                throw new SmsDriverNotSupportPatternException("Driver {$this->driverName} does not support pattern sms");
            }
            return $this->driver->sendByPattern($this->to[0], $this->patternName);
        }
        return $this->driver->send($this->text, $this->to);
    }

    public function pattern(string $patternName): self
    {
        $this->patternName = $patternName;
        return $this;
    }
}
