<?php

namespace domain\Producer\Producer;

use domain\Setting\AdminSettingBag;
use domain\_\AbstractService;
use domain\_\ManagerInterface;

class ProducerManager extends AbstractService implements ManagerInterface
{
    protected AdminSettingBag $adminSettingBag;
    protected ProducerRepository $producerRepository;

    public function loadDependencies(): void
    {
        $this->adminSettingBag = $this->loadService(AdminSettingBag::class);
        $this->producerRepository = $this->loadService(ProducerRepository::class);
    }

    public function readAlertMessage(Producer $producer)
    {
        $producer->setAlertMessageReadAt(new \DateTime());
        return $producer->save();
    }

    public function sendEmailNewProducer(Producer $producer): void
    {
        \Yii::$app->mailerService->sendAdmin(
            'Nouveau producteur',
            'new-producer',
            [
                'producer' => $producer
            ]
        );
    }

    public function getMaximumNumberProducers(): ?int
    {
        return $this->adminSettingBag->get('maximumNumberProducers');
    }

    public function isProducerSignupOpen(): bool
    {
        $maximumNumberProducers = $this->getMaximumNumberProducers();

        return !$maximumNumberProducers
            || $maximumNumberProducers > $this->producerRepository->countCacheProducersActiveWithTurnover();
    }

    public function getProducerSignupRemainingPlaces(): int
    {
        return max($this->getMaximumNumberProducers()
            - $this->producerRepository->countCacheProducersActiveWithTurnover(), 0);
    }
}