<?php

declare(strict_types=1);

namespace MauticPlugin\DealFlowBundle\Compat;

use Mautic\CoreBundle\Helper\AppVersion;

/**
 * Centralized Mautic version detection and compatibility adapter.
 *
 * All cross-version branching (5.x vs 6.x vs 7.x) is funneled through this
 * single service so the rest of the plugin never has to inspect
 * MAUTIC_VERSION or call interface_exists() directly.
 *
 * In production DI (Config/config.php) this class is instantiated with
 * mautic.helper.app_version injected; it calls getVersion() to obtain the
 * Mautic version string.
 *
 * In tests, use the string constructor directly: new MauticVersionAdapter('7.1.0').
 */
final class MauticVersionAdapter
{
    private readonly string $version;
    private readonly int $majorVersion;

    /**
     * @param AppVersion|string $versionOrHelper
     *   Pass a string version (e.g. "7.1.0") for testing, or the AppVersion
     *   service for production DI.
     */
    public function __construct(AppVersion|string $versionOrHelper)
    {
        $this->version = $versionOrHelper instanceof AppVersion
            ? $versionOrHelper->getVersion()
            : $versionOrHelper;

        $parts = explode('.', $this->version);
        $this->majorVersion = (int) ($parts[0] ?? 0);
    }

    /**
     * Returns the full Mautic version string (e.g. "7.1.0").
     */
    public function getVersion(): string
    {
        return $this->version;
    }

    /**
     * Returns the Mautic major version integer (5, 6, or 7).
     */
    public function getMajorVersion(): int
    {
        return $this->majorVersion;
    }

    /**
     * Returns true when running Mautic 7.0 or higher.
     *
     * Use this to gate code that relies on APIs introduced in Mautic 7.
     */
    public function isVersion7OrAbove(): bool
    {
        return $this->majorVersion >= 7;
    }

    /**
     * Returns true when Mautic\CoreBundle\Model\GlobalSearchInterface is
     * available in the current Mautic installation.
     *
     * The interface was introduced in Mautic 7.x. On 5.x/6.x the
     * GlobalSearchCompat shim provides an empty stand-in so DealModel can
     * still implement it without a fatal error.
     */
    public function isGlobalSearchInterfaceAvailable(): bool
    {
        return interface_exists(\Mautic\CoreBundle\Model\GlobalSearchInterface::class);
    }
}
