<?php

namespace Ignite\Core\Services\Google\Analytics;

use BadMethodCallException;
use Google_Client;
use Ignite\Core\Services\Google\Analytics\Adapter\AdapterGA4;
use Ignite\Core\Services\Google\Analytics\Adapter\AdapterInterface;
use Ignite\Core\Services\Google\Analytics\Adapter\AdapterUA;

class Client extends Google_Client
{
    /**
     * The different supported API versions of Google Analytics.
     */
    public const VERSION_UA = 'UA';
    public const VERSION_GA4 = 'GA4';

    /**
     * @var string
     */
    protected $version;

    /**
     * @var \Ignite\Core\Services\Google\Analytics\Adapter\AdapterInterface
     */
    protected $adapter;

    /**
     * @param mixed $name
     * @param mixed $arguments
     */
    public function __call($name, $arguments)
    {
        if (method_exists($this->adapter, $name)) {
            return $this->adapter->$name(...$arguments);
        }
        throw new BadMethodCallException("Method {$name} does not exist.");
    }

    /**
     * {@inheritdoc}
     */
    public function __construct(array $config = [])
    {
        $this->setVersion($this->detectVersion());
        parent::__construct($config);
    }

    /**
     * @return string
     */
    public function getVersion(): string
    {
        return $this->version;
    }

    /**
     * @param string $version
     */
    public function setVersion(string $version): void
    {
        $this->version = $version;

        if (self::VERSION_UA == $this->version) {
            $this->adapter = resolve(AdapterUA::class, ['client' => $this]);
        } else {
            $this->adapter = resolve(AdapterGA4::class, ['client' => $this]);
        }
    }

    /**
     * Auto-determines if using UA or GA4.
     *
     * @return string
     */
    protected function detectVersion(): string
    {
        if (config('core.google.analytics.property')) {
            // if property id is available, then use latest GA4
            return self::VERSION_GA4;
        } elseif (config('core.google.analytics.view')) {
            return self::VERSION_UA;
        }

        return self::VERSION_GA4;
    }
}
