<?php

declare(strict_types=1);

/**
 * Cette class vérifie le token de connexion.
 */
class AccessChecker
{
    /**
     * @param array<string, string> $headers
     *
     * @throws MvsUnauthorizedException
     */
    public function check(array $headers): OAuthAccessToken
    {
        $accessToken = null;
        $headerKey = isset($headers['Authorization']) ? 'Authorization' : 'authorization';

        if (isset($headers[$headerKey])) {
            // si Bearer dans la chaine, on le supprimer pour récuperer uniquement le token
            if (0 == strpos($headers[$headerKey], 'Bearer')) {
                $token = trim(str_replace('Bearer', '', $headers['Authorization']));
                try {
                    $accessToken = OAuthAccessToken::getByToken($token);
                } catch (PrestaShopDatabaseException $e) {
                    $accessToken = null;
                } catch (PrestaShopException $e) {
                    $accessToken = null;
                }
            }
        }

        if (!$accessToken || $accessToken->expires < time()) {
            throw new MvsUnauthorizedException();
        }

        return $accessToken;
    }
}
