<?php

namespace common\logic\User\User\Service;

use common\logic\AbstractService;
use common\logic\User\User\Model\User;
use common\logic\User\UserProducer\Repository\UserProducerRepository;
use common\logic\User\UserProducer\Service\UserProducerBuilder;
use common\logic\ManagerInterface;

class NewsletterManager extends AbstractService implements ManagerInterface
{
    protected UserProducerRepository $userProducerRepository;
    protected UserProducerBuilder $userProducerBuilder;

    public function loadDependencies(): void
    {
        $this->userProducerRepository = $this->loadService(UserProducerRepository::class);
        $this->userProducerBuilder = $this->loadService(UserProducerBuilder::class);
    }

    public function isUserSubscribedNewsletter(User $user = null): bool
    {
        if($user) {
            $userProducer = $this->userProducerRepository->findOneUserProducer($user);
            if($userProducer && $userProducer->newsletter) {
                return true;
            }
        }

        return false;
    }

    public function subscribeUserNewsletter(User $user): bool
    {
        $userProducer = $this->userProducerBuilder->createUserProducerIfNotExist($user, $this->getProducerContext());
        return $this->userProducerBuilder->updateUserProducerNewsletter($userProducer, true);
    }

    public function unsubscribeUserNewsletter(User $user): bool
    {
        $userProducer = $this->userProducerRepository->findOneUserProducer($user);
        if($userProducer) {
            return $this->userProducerBuilder->updateUserProducerNewsletter($userProducer, false);
        }

        return false;
    }
}