<?php

namespace App\Security;

use App\Entity\User as AppUser;
use Symfony\Component\Security\Core\Security;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Security\Core\User\UserCheckerInterface;
use Symfony\Component\Security\Core\Authentication\Token\SwitchUserToken;
use Symfony\Component\Security\Core\Exception\CustomUserMessageAccountStatusException;

class UserChecker implements UserCheckerInterface
{
    private Security $security;

    public function __construct(Security $security)
    {
        $this->security = $security;
    }

    public function checkPreAuth(UserInterface $user)
    {
        if (!$user instanceof AppUser) {
            return;
        }
    }

    public function checkPostAuth(UserInterface $user)
    {
        if (!$user instanceof AppUser) {
            return;
        }
        $token = $this->security->getToken();
        $isNoImpersonation = ($token == null || $token->getUser() == $user);



        if ($user->getIsDesactivated() && $isNoImpersonation) {
            throw new CustomUserMessageAccountStatusException(
                //Account desactivated, you can\'t log in with anymore. Contact an admin to restore your access
                'exception_user_account_desactivated'
            );
        }

        if (!$user->isVerified() && $isNoImpersonation) {
            throw new CustomUserMessageAccountStatusException(
                //'Please clic on the validation link you got on your mailbox.'
                'exception_user_clic_link_mailbox'
            );
        }

        if ($user->getMainGroup() === null || $user->getMainRank() === null) {
            if ($user->hasRole('ROLE_ADMIN')) {
                throw new CustomUserMessageAccountStatusException(
                    'exception_user_no_group_and_or_no_rank_admin'
                );
            }
            throw new CustomUserMessageAccountStatusException(
                'exception_user_no_group_and_or_no_rank'
            );
        }
    }
}
