<?php

declare(strict_types=1);

/*
 * Chill is a software for social workers
 *
 * For the full copyright and license information, please view
 * the LICENSE file that was distributed with this source code.
 */

namespace Chill\MainBundle\Action\User\UpdateProfile;

use Chill\MainBundle\Entity\User;
use Chill\MainBundle\Notification\NotificationFlagManager;
use Chill\MainBundle\Validation\Constraint\PhonenumberConstraint;
use libphonenumber\PhoneNumber;
use Symfony\Component\Validator\Constraints as Assert;

final class UpdateProfileCommand
{
    public array $notificationFlags = [];

    public function __construct(
        #[PhonenumberConstraint]
        public ?PhoneNumber $phonenumber,
        #[Assert\Choice(choices: ['fr', 'nl'], message: 'Locale must be either "fr" or "nl"')]
        public string $locale = 'fr',
    ) {}

    public static function create(User $user, NotificationFlagManager $flagManager): self
    {
        $updateProfileCommand = new self($user->getPhonenumber(), $user->getLocale());

        foreach ($flagManager->getAllNotificationFlagProviders() as $provider) {
            $updateProfileCommand->setNotificationFlag(
                $provider->getFlag(),
                User::NOTIF_FLAG_IMMEDIATE_EMAIL,
                $user->isNotificationSendImmediately($provider->getFlag())
            );
            $updateProfileCommand->setNotificationFlag(
                $provider->getFlag(),
                User::NOTIF_FLAG_DAILY_DIGEST,
                $user->isNotificationDailyDigest($provider->getFlag())
            );
        }

        return $updateProfileCommand;
    }

    /**
     * @param User::NOTIF_FLAG_IMMEDIATE_EMAIL|User::NOTIF_FLAG_DAILY_DIGEST $kind
     */
    private function setNotificationFlag(string $type, string $kind, bool $value): void
    {
        if (!array_key_exists($type, $this->notificationFlags)) {
            $this->notificationFlags[$type] = ['immediate_email' => true, 'daily_digest' => false];
        }

        $k = match ($kind) {
            User::NOTIF_FLAG_IMMEDIATE_EMAIL => 'immediate_email',
            User::NOTIF_FLAG_DAILY_DIGEST => 'daily_digest',
        };

        $this->notificationFlags[$type][$k] = $value;
    }
}
