<?php declare(strict_types=1);
/**
 * This file is part of the SplendidBear Websites' projects.
 *
 * Copyright (c) 2026 @ www.splendidbear.org
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace App\Service;

use App\Entity\PlayedGame;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bundle\SecurityBundle\Security;
use Symfony\Component\HttpFoundation\RequestStack;

/**
 * Class ResolveUserNamesService
 *
 * This only works when a restored game is started
 *
 * @package  App\Service
 * @author   Lang <https://www.splendidbear.org>
 * @category Class
 * @license  https://www.gnu.org/licenses/lgpl-3.0.en.html GNU Lesser General Public License
 * @link     www.splendidbear.org
 * @since    2026. 04. 19.
 */
readonly final class ResolveUserNamesService
{
    public function __construct(
        private EntityManagerInterface $em,
        private RequestStack           $requestStack,
        private Security               $security,
    ) {
    }

    public function opponentName(?string $gameAssoc = null): string
    {
        $userName = $this->resolveUserName();

        if (null === $gameAssoc) {
            return '';
        }

        if (null === $game = $this->em->getRepository(PlayedGame::class)->findOneByGameAssoc($gameAssoc)) {
            return '';
        }

        return $this->resolveOpponentName($game, $userName);
    }

    public function resolveUserName(): string
    {
        $user = $this->security->getUser();

        if (null !== $user) {
            return $user->getUserIdentifier();
        }

        $session = $this->requestStack->getCurrentRequest()->getSession();

        if (!$session->isStarted()) {
            $session->start();
        }

        return "anon_{$session->getId()}";
    }

    private function resolveOpponentName(PlayedGame $game, string $myUserName): string
    {
        $redName = $game->red?->getUsername();
        $blueName = $game->blue?->getUsername();
        $redAnonName = $game->redAnon?->userName;
        $blueAnonName = $game->blueAnon?->userName;

        $isRed = $myUserName === $redName || $myUserName === $redAnonName;
        $isBlue = $myUserName === $blueName || $myUserName === $blueAnonName;

        if ($isRed) {
            return $blueName ?? ('' !== ($blueAnonName ?? '') ? 'Guest' : '');
        }

        if ($isBlue) {
            return $redName ?? ('' !== ($redAnonName ?? '') ? 'Guest' : '');
        }

        return '';
    }
}
