<?php

declare(strict_types=1);

/*
 * Chill is a software for social workers
 *
 * For the full copyright and license information, please view
 * the LICENSE file that was distributed with this source code.
 */

namespace Chill\DocStoreBundle\Security\Guard;

use Chill\DocStoreBundle\Entity\StoredObject;
use Chill\DocStoreBundle\Security\Authorization\StoredObjectRoleEnum;
use Lexik\Bundle\JWTAuthenticationBundle\Services\JWTTokenManagerInterface;
use Symfony\Component\Security\Core\Security;

/**
 * Provide a JWT Token which will be valid for viewing or editing a document.
 */
final readonly class JWTDavTokenProvider implements JWTDavTokenProviderInterface
{
    public function __construct(
        private JWTTokenManagerInterface $JWTTokenManager,
        private Security $security,
    ) {}

    public function createToken(StoredObject $storedObject, StoredObjectRoleEnum $roleEnum): string
    {
        return $this->JWTTokenManager->createFromPayload($this->security->getUser(), [
            'dav' => 1,
            'e' => match ($roleEnum) {
                StoredObjectRoleEnum::SEE => 0,
                StoredObjectRoleEnum::EDIT => 1,
            },
            'so' => $storedObject->getUuid(),
        ]);
    }

    public function getTokenExpiration(string $tokenString): \DateTimeImmutable
    {
        $jwt = $this->JWTTokenManager->parse($tokenString);

        return \DateTimeImmutable::createFromFormat('U', (string) $jwt['exp']);
    }
}
