<?php

declare(strict_types=1);

/*
 * This file is part of the VITICORE2 package.
 *
 * (c) CP Creation <web@cpcreation.fr>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace CpCreation\VitiCore\Commerce\Catalog\Api\Security;

use CpCreation\VitiCore\Commerce\Catalog\Configuration\CatalogIntegrationConfiguration;
use Symfony\Component\Security\Core\Exception\BadCredentialsException;
use Symfony\Component\Security\Core\User\InMemoryUser;
use Symfony\Component\Security\Http\AccessToken\AccessTokenHandlerInterface;
use Symfony\Component\Security\Http\Authenticator\Passport\Badge\UserBadge;

final readonly class CommerceAccessTokenHandler implements AccessTokenHandlerInterface
{
    public function __construct(
        private CatalogIntegrationConfiguration $configuration,
        private CatalogHubJwtVerifier $hubJwtVerifier,
    ) {}

    public function getUserBadgeFrom(#[\SensitiveParameter] string $accessToken): UserBadge
    {
        if (!$this->configuration->isEnabled()
            || (!$this->configuration->matchesApiToken($accessToken) && !$this->hubJwtVerifier->isValid($accessToken))
        ) {
            throw new BadCredentialsException('Invalid credentials.');
        }

        $identifier = 'commerce-sync:' . $this->configuration->instanceId();

        return new UserBadge(
            $identifier,
            static fn(string $userIdentifier): InMemoryUser => new InMemoryUser(
                $userIdentifier,
                null,
                ['ROLE_COMMERCE_SYNC'],
            ),
        );
    }
}
