<?php

namespace domain\User\User;

use domain\User\UserProducer\UserProducerBuilder;
use domain\User\UserProducer\UserProducerRepository;
use domain\_\AbstractService;
use domain\_\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;
    }
}