<?php

namespace App\User\Action\Handler;

use App\User\Action\Command\SaveUserMediaPreferencesCommand;
use App\User\Action\Result\SaveUserDownloadPreferencesResult;
use App\User\Action\Result\SaveUserMediaPreferencesResult;
use App\User\Framework\Entity\User;
use App\User\Framework\Entity\UserPreference;
use App\User\Framework\Repository\PreferencesRepository;
use Doctrine\ORM\EntityManagerInterface;
use OneToMany\RichBundle\Contract\CommandInterface as C;
use OneToMany\RichBundle\Contract\HandlerInterface;
use OneToMany\RichBundle\Contract\ResultInterface as R;
use Symfony\Bundle\SecurityBundle\Security;

/** @implements HandlerInterface<SaveUserMediaPreferencesCommand> */
class SaveUserCalendarPreferencesHandler implements HandlerInterface
{
    public function __construct(
        private readonly EntityManagerInterface $entityManager,
        private readonly PreferencesRepository $preferenceRepository,
        private readonly Security $token,
    ) {}

    public function handle(C $command): R
    {
        /** @var User $user */
        $user = $this->token->getUser();

        foreach ($command as $preference => $value) {
            if ($user->hasUserPreference($preference)) {
                $user->updateUserPreference($preference, $value);
                $this->entityManager->flush();
                continue;
            }

            $preference = $this->preferenceRepository->find($preference);

            $user->addUserPreference(
                (new UserPreference())
                    ->setUser($user)
                    ->setPreference($preference)
                    ->setPreferenceValue($value)
            );
        }

        $this->entityManager->flush();

        return new SaveUserDownloadPreferencesResult($user->getDownloadPreferences());
    }
}
