<?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\Tests\Entity;

use Chill\MainBundle\Entity\User;
use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase;

/**
 * @internal
 *
 * @coversNothing
 */
class UserNotificationFlagsPersistenceTest extends KernelTestCase
{
    public function testFlushPersistsNotificationFlagsChanges(): void
    {
        self::bootKernel();
        $em = self::getContainer()->get('doctrine')->getManager();

        $user = new User();
        $user->setUsername('user_'.bin2hex(random_bytes(4)));
        $user->setLabel('Test User');
        $user->setPassword('secret');

        // Étape 1: créer et persister l’utilisateur
        $em->persist($user);
        $em->flush();
        $id = $user->getId();
        self::assertNotNull($id, 'User should have an ID after flush');

        try {
            // Sanity check: par défaut, pas de daily digest pour "alerts"
            self::assertFalse($user->isNotificationDailyDigest('alerts'));

            // Étape 2: activer le daily digest -> setNotificationFlagElement réassigne la propriété
            $user->setNotificationDailyDigest('alerts', true);
            $em->flush(); // persist le changement
            $em->clear(); // simule un nouveau cycle de requête

            // Étape 3: recharger depuis la base et vérifier la persistance
            /** @var User $reloaded */
            $reloaded = $em->find(User::class, $id);
            self::assertNotNull($reloaded);
            self::assertTrue(
                $reloaded->isNotificationDailyDigest('alerts'),
                'Daily digest flag should be persisted'
            );

            // Étape 4: modifier via setNotificationFlagData (remplacement du tableau)
            // Cette méthode doit réassigner la propriété (copie -> réassignation)
            $reloaded->setNotificationImmediately('alerts', true);
            $reloaded->setNotificationDailyDigest('alerts', false);
            $em->flush();
            $em->clear();

            /** @var User $reloaded2 */
            $reloaded2 = $em->find(User::class, $id);
            self::assertNotNull($reloaded2);

            // Le daily digest n’est plus actif, seul immediate-email est présent
            self::assertFalse($reloaded2->isNotificationDailyDigest('alerts'));
            self::assertTrue($reloaded2->isNotificationSendImmediately('alerts'));
        } finally {
            // Nettoyage
            $managed = $em->find(User::class, $id);
            if (null !== $managed) {
                $em->remove($managed);
                $em->flush();
            }
            $em->clear();
        }
    }
}
