<?php

namespace DMD\LaLigaApi\Service\League\joinTeam;

use DMD\LaLigaApi\Enum\Role;
use DMD\LaLigaApi\Repository\CustomRoleRepository;
use DMD\LaLigaApi\Repository\LeagueRepository;
use DMD\LaLigaApi\Repository\TeamRepository;
use DMD\LaLigaApi\Service\Common\AuthorizeRequest;
use DMD\LaLigaApi\Service\Common\NotificationFactory;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\HttpException;

class HandleCaptainRequest
{
    public function __construct(
        public AuthorizeRequest $authorizeRequest,
        public CustomRoleRepository          $customRoleRepository,
        public LeagueRepository         $leagueRepository,
        public TeamRepository         $teamRepository,
        public NotificationFactory $notificationFactory
    ){}

    public function __invoke(
        Request $request,
        int $leagueId,
        int $teamId
    ): JsonResponse
    {
        $leagueToJoinEntity = $this->leagueRepository->find($leagueId);
        if (is_null($leagueToJoinEntity))
        {
            throw new HttpException(Response::HTTP_NOT_FOUND, "Liga con id: $leagueId no ha sido encontrada");
        }
        $requestingUserEntity = $this->authorizeRequest->teamCaptainRequest($leagueId, $teamId);
        $userToNotifyEntity = $this->customRoleRepository->findUserByRoleName($leagueId . Role::LEAGUE_PRESIDENT->value);
        if (is_null($userToNotifyEntity))
        {
            throw new HttpException(Response::HTTP_NOT_FOUND, "No se ha encontrado presidente de la liga con id $leagueId");
        }

        $teamToJoinEntity = $this->teamRepository->find($teamId);
        if (is_null($teamToJoinEntity))
        {
            throw new HttpException(Response::HTTP_NOT_FOUND, 'Equipo no encontrado.');
        }
        $this->notificationFactory->teamCaptainRequest(
            $requestingUserEntity,
            $userToNotifyEntity,
            $request->toArray()['message'],
            $leagueToJoinEntity,
            $teamId
        );
        return new JsonResponse(
            data: [
                'success' => true,
                'message' => 'La solicitud ha sido enviada correctamente.'
            ],
            status: Response::HTTP_OK
        );
    }
}