<?php

namespace DMD\LaLigaApi\Service\Common;

use DMD\LaLigaApi\Entity\League;
use DMD\LaLigaApi\Entity\User;
use DMD\LaLigaApi\Enum\Role;
use DMD\LaLigaApi\Repository\CustomRoleRepository;
use DMD\LaLigaApi\Repository\LeagueRepository;
use Symfony\Bundle\SecurityBundle\Security;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\HttpException;

class AuthorizeRequest
{
    public function __construct(
        public Security $security,
        public CustomRoleRepository $customRoleRepository,
        public LeagueRepository $leagueRepository
    )
    {}

    public function authorizeLeaguePresident(int $leagueId): void
    {
        $userEntity = $this->security->getUser();
        if (is_null($userEntity))
        {
            throw new HttpException(Response::HTTP_FORBIDDEN, "Unauthorized.");
        }
        $customRole = $this->customRoleRepository->findBy([
            'name' => Role::LEAGUE_PRESIDENT->value,
            'user' => $userEntity,
            'entityId' => $leagueId
        ]);
        if (is_null($customRole))
        {
            throw new HttpException(Response::HTTP_FORBIDDEN, "Forbidden");
        }
    }

    public function teamCaptainRequest(int $leagueId, $teamId): User
    {
        $requestingUserEntity = $this->security->getUser();
        if (!$requestingUserEntity instanceof User)
        {
            throw new HttpException(Response::HTTP_FORBIDDEN, "Unauthorized");
        }
        $captainCustomRole = $this->customRoleRepository->findBy([
            'name' => Role::TEAM_CAPTAIN->value,
            'entityId' => $teamId
        ]);
        if (!is_null($captainCustomRole))
        {
            throw new HttpException(Response::HTTP_FORBIDDEN, "Equipo con id: $teamId ya tiene capitan");
        }
        $leagueMemberRole = $this->customRoleRepository->findBy([
            'name' => Role::LEAGUE_MEMBER->value,
            'user' => $requestingUserEntity,
            'entityId' => $leagueId
        ]);
        if (is_null($leagueMemberRole))
        {
            throw new HttpException(Response::HTTP_FORBIDDEN, "Debes ser miembro de la liga antes de solicitar ser capitan.");
        }
        return $requestingUserEntity;
    }

    public function isLeaguePresident(int $leagueId, User $leagueAdmin): bool
    {
        $customRole = $this->customRoleRepository->findBy([
                'name' => Role::LEAGUE_PRESIDENT->value,
                'entityId' => $leagueId,
                'user' => $leagueAdmin
            ]
        );
        if (is_null($customRole))
        {
            throw new HttpException(Response::HTTP_FORBIDDEN,'Forbidden.');
        }
        return true;
    }
}