<?php

namespace KupShop\AutomationConfiguratorBundle\Configurator\Users\Actions;

use KupShop\AutomationConfiguratorBundle\Configurator\BuilderDefinitions\TriggersActions\TrigActDefinition;
use KupShop\AutomationConfiguratorBundle\Configurator\BuilderDefinitions\TriggersActions\TrigActDefinitionCheckbox;
use KupShop\AutomationConfiguratorBundle\Configurator\Generic\Actions\GenericAction;
use KupShop\AutomationConfiguratorBundle\Configurator\Interfaces\Actions\ActionInterface;
use KupShop\AutomationConfiguratorBundle\Configurator\Interfaces\Config\ActionConfig;
use KupShop\AutomationConfiguratorBundle\Configurator\Users\UsersContext;
use KupShop\AutomationConfiguratorBundle\Event\TriggerEvent;
use KupShop\UserBundle\Util\UserConsent;
use Symfony\Contracts\Service\Attribute\Required;

class SetUserNewletter extends GenericAction implements ActionInterface, UsersContext
{
    public const NAME = 'set_user_newsletter';

    #[Required]
    public UserConsent $userConsent;

    public function getConfig()
    {
        return (new TrigActDefinition())
            ->setLabel('Nastavit přihlášení k newsletteru')
            ->addField(
                (new TrigActDefinitionCheckbox())
                ->setName('newsletter')
                    ->setTitle('Ano/Ne')
            )->build();
    }

    public function run(ActionConfig $actionConfig, $context, TriggerEvent $triggerEvent): bool
    {
        $newsletter = $actionConfig->getField('newsletter')?->getValue();

        if ($context['u_get_news'] === $newsletter) {
            // už newsletter má/nemá
            return false;
        }

        if ($newsletter) {
            $this->userConsent->updateNewsletter($context['id'], $newsletter, false, true);
        }

        return true;
    }

    public function getLog(ActionConfig $actionConfig, $context)
    {
        $newsletter = $actionConfig->getField('newsletter')?->getValue();
        if ($newsletter == 'Y') {
            return "Uživatel {$context['u_log_info']} byl přihlášen k newsletteru";
        }

        return "Uživatel {$context['u_log_info']} byl odhlášen z newsletteru";
    }
}
