<?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 Action\User\UpdateProfile;

use Chill\MainBundle\Action\User\UpdateProfile\UpdateProfileCommand;
use Chill\MainBundle\Action\User\UpdateProfile\UpdateProfileCommandHandler;
use Chill\MainBundle\Entity\User;
use libphonenumber\PhoneNumber;
use PHPUnit\Framework\TestCase;

/**
 * @internal
 *
 * @coversNothing
 */
final class UpdateProfileCommandHandlerTest extends TestCase
{
    public function testUpdateProfileWithNullPhoneAndFlags(): void
    {
        $user = new User();

        // Pre-set some flags to opposite values to check they are updated
        $flag = 'tickets';
        $user->setNotificationImmediately($flag, true);
        $user->setNotificationDailyDigest($flag, true);

        $command = new UpdateProfileCommand(null);
        $command->notificationFlags = [
            $flag => [
                'immediate_email' => false,
                'daily_digest' => false,
            ],
        ];

        (new UpdateProfileCommandHandler())->updateProfile($user, $command);

        self::assertNull($user->getPhonenumber(), 'Phone should be set to null');
        self::assertFalse($user->isNotificationSendImmediately($flag));
        self::assertFalse($user->isNotificationDailyDigest($flag));
    }

    public function testUpdateProfileWithPhoneAndMultipleFlags(): void
    {
        $user = new User();

        $phone = new PhoneNumber();
        $phone->setCountryCode(33); // France
        $phone->setNationalNumber(612345678);

        $command = new UpdateProfileCommand($phone);
        $command->notificationFlags = [
            'reports' => [
                'immediate_email' => true,
                'daily_digest' => false,
            ],
            'activities' => [
                'immediate_email' => false,
                'daily_digest' => true,
            ],
        ];

        (new UpdateProfileCommandHandler())->updateProfile($user, $command);

        // Phone assigned
        self::assertInstanceOf(PhoneNumber::class, $user->getPhonenumber());
        self::assertSame(33, $user->getPhonenumber()->getCountryCode());
        self::assertSame('612345678', (string) $user->getPhonenumber()->getNationalNumber());

        // Flags applied
        self::assertTrue($user->isNotificationSendImmediately('reports'));
        self::assertFalse($user->isNotificationDailyDigest('reports'));

        self::assertFalse($user->isNotificationSendImmediately('activities'));
        self::assertTrue($user->isNotificationDailyDigest('activities'));
    }
}
