<?php

namespace App\Services\Marketplace;

use App\Services\Marketplace\Exceptions\DependencyException;

/**
 * Checks whether a package's CMS version constraints are satisfied.
 */
class DependencyChecker
{
    /**
     * Assert that the running CMS version satisfies the package's min/max constraints.
     *
     * @param array $manifest Keys: min_cms_version (required), max_cms_version (optional).
     * @throws DependencyException when the constraint is not met.
     */
    public function checkCmsVersion(array $manifest): void
    {
        $current = cms_version();

        $min = trim((string) ($manifest['min_cms_version'] ?? '0'));
        if ($min !== '' && $min !== '0') {
            if (!version_compare($current, $min, '>=')) {
                throw new DependencyException(
                    "This package requires CMS version {$min} or higher (current: {$current})."
                );
            }
        }

        $max = trim((string) ($manifest['max_cms_version'] ?? ''));
        if ($max !== '') {
            if (!version_compare($current, $max, '<=')) {
                throw new DependencyException(
                    "This package is not compatible with CMS version {$current} (max supported: {$max})."
                );
            }
        }
    }

    /**
     * Return true/false instead of throwing – useful for preview rendering.
     */
    public function isCmsVersionCompatible(array $manifest): bool
    {
        try {
            $this->checkCmsVersion($manifest);
            return true;
        } catch (DependencyException $e) {
            return false;
        }
    }

    /**
     * Return human-readable compatibility warnings without throwing.
     *
     * @return string[]
     */
    public function getCmsWarnings(array $manifest): array
    {
        $warnings = [];
        $current  = cms_version();

        $min = trim((string) ($manifest['min_cms_version'] ?? '0'));
        if ($min !== '' && $min !== '0' && !version_compare($current, $min, '>=')) {
            $warnings[] = "Requires CMS ≥ {$min} (current: {$current})";
        }

        $max = trim((string) ($manifest['max_cms_version'] ?? ''));
        if ($max !== '' && !version_compare($current, $max, '<=')) {
            $warnings[] = "Not compatible with CMS {$current} (max: {$max})";
        }

        return $warnings;
    }
}
