<?php

declare(strict_types=1);

namespace App\Module\Mail\Infrastructure\Security;

use App\Shared\Domain\Contract\UserInterface as SharedUserInterface;
use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
use Symfony\Component\Security\Core\User\UserInterface;

final readonly class MailAccessChecker
{
    public function __construct(
        private AuthorizationCheckerInterface $authorizationChecker,
    ) {}

    /**
     * Verifie que l'utilisateur courant peut acceder aux endpoints mail.
     * Autorise : ROLE_USER, ROLE_ADMIN.
     *
     * @throws AccessDeniedException
     */
    public function ensureCanAccessMail(?UserInterface $user): void
    {
        if (!$user instanceof SharedUserInterface) {
            throw new AccessDeniedException('Authentication required');
        }

        $roles = $user->getRoles();

        if (!in_array('ROLE_USER', $roles, true) && !in_array('ROLE_ADMIN', $roles, true)) {
            throw new AccessDeniedException('ROLE_USER required');
        }
    }

    /**
     * Verifie que l'utilisateur est ROLE_ADMIN.
     *
     * @throws AccessDeniedException
     */
    public function ensureIsAdmin(?UserInterface $user): void
    {
        if (!$user instanceof SharedUserInterface || !$this->authorizationChecker->isGranted('ROLE_ADMIN')) {
            throw new AccessDeniedException('Admin only');
        }
    }
}
