<?php

namespace common\logic\Feature\Feature;

use common\logic\AbstractChecker;
use common\logic\Feature\FeatureProducer\FeatureProducerRepository;
use yii\base\ErrorException;

class FeatureChecker extends AbstractChecker
{
    protected FeatureRepository $featureRepository;
    protected FeatureProducerRepository $featureProducerRepository;

    public function loadDependencies(): void
    {
        $this->featureRepository = $this->loadService(FeatureRepository::class);
        $this->featureProducerRepository = $this->loadService(FeatureProducerRepository::class);
    }

    public function isEnabled(string $aliasFeature): bool
    {
        $feature = $this->featureRepository->findOneFeatureByAlias($aliasFeature);
        if(!$feature) {
            throw new ErrorException("Fonctionnalité avec l'alias '".$aliasFeature."' non trouvée");
        }

        if(!$feature->status) {
            return false;
        }

        $featureProducer = $this->featureProducerRepository->findOneFeatureProducer($feature);
        if(!$featureProducer || is_null($featureProducer->status)) {
            if($feature->is_paid_feature || $feature->only_for_selected_producers) {
                return false;
            }

            return $feature->status;
        }
        else {
            return $featureProducer->status;
        }
    }

    public function isDisabled(string $aliasFeature): bool
    {
        return !$this->isEnabled($aliasFeature);
    }
}