<?php

declare(strict_types=1);

namespace Flowaxy\Domain\Plugin\Services;

use function constant;
use function defined;
use function ltrim;
use function version_compare;

// Резолвер версій плагінів
final class PluginVersionResolver
{
    public function checkEngineCompatibility(
        string $pluginVersion,
        ?string $minEngineVersion,
        ?string $maxEngineVersion,
        string $currentEngineVersion
    ): array {
        $errors = [];
        $warnings = [];

        if ($minEngineVersion !== null) {
            if (!$this->versionCompare($currentEngineVersion, $minEngineVersion, '>=')) {
                $errors[] = "Требуется версия движка >= {$minEngineVersion}, текущая: {$currentEngineVersion}";
            }
        }

        if ($maxEngineVersion !== null) {
            if (!$this->versionCompare($currentEngineVersion, $maxEngineVersion, '<=')) {
                $errors[] = "Требуется версия движка <= {$maxEngineVersion}, текущая: {$currentEngineVersion}";
            }
        }

        return [
            'compatible' => empty($errors),
            'errors' => $errors,
            'warnings' => $warnings,
        ];
    }

    public function checkDependencies(array $dependencies, array $installedPlugins): array
    {
        $errors = [];
        $missing = [];

        foreach ($dependencies as $dependency) {
            $slug = $dependency['slug'] ?? '';
            $requiredVersion = $dependency['version'] ?? null;

            if (empty($slug)) {
                continue;
            }

            if (!isset($installedPlugins[$slug])) {
                $missing[] = $slug;
                $errors[] = "Отсутствует зависимость: {$slug}" . ($requiredVersion ? " (версия {$requiredVersion})" : '');
                continue;
            }

            if ($requiredVersion !== null) {
                $installedVersion = $installedPlugins[$slug];
                if (!$this->versionCompare($installedVersion, $requiredVersion, '>=')) {
                    $errors[] = "Несовместимая версия зависимости {$slug}: требуется >= {$requiredVersion}, установлена {$installedVersion}";
                }
            }
        }

        return [
            'compatible' => empty($errors),
            'errors' => $errors,
            'missing' => $missing,
        ];
    }

    private function versionCompare(string $version1, string $version2, string $operator): bool
    {
        $version1 = ltrim($version1, 'v');
        $version2 = ltrim($version2, 'v');

        $result = version_compare($version1, $version2);

        return match ($operator) {
            '>=' => $result >= 0,
            '<=' => $result <= 0,
            '==' => $result === 0,
            '>' => $result > 0,
            '<' => $result < 0,
            default => false,
        };
    }

    public function getCurrentEngineVersion(): string
    {
        if (defined('FLOWAXY_VERSION')) {
            return (string) constant('FLOWAXY_VERSION');
        }

        return '1.0.0';
    }
}
