<?php

namespace Modules\WhatsApp\Entities\Services;

use Modules\WhatsApp\Entities\Contracts\WaTransport;
use Modules\WhatsApp\Entities\WaChannel;

/**
 * Resolves the right transport driver for a channel. New transports (Twilio,
 * other BSPs) are added purely by registering them in config('whatsapp.drivers')
 * — nothing else in the pipeline changes.
 */
class TransportManager
{
    /** @var array<string, WaTransport> */
    private array $resolved = [];

    public function driver(WaChannel $channel): WaTransport
    {
        return $this->byName($channel->driver);
    }

    public function byName(string $name): WaTransport
    {
        if (isset($this->resolved[$name])) {
            return $this->resolved[$name];
        }

        $map = config('whatsapp.drivers', []);
        if (empty($map[$name]) || !class_exists($map[$name])) {
            throw new \RuntimeException("Unknown WhatsApp driver: {$name}");
        }

        $instance = app($map[$name]);
        if (!$instance instanceof WaTransport) {
            throw new \RuntimeException("Driver {$name} must implement WaTransport.");
        }

        return $this->resolved[$name] = $instance;
    }
}
