<?php

namespace Modules\Common\Support\Wechat\OpenPlatform;

use EasyWeChat\OpenPlatform\Application;

class OPApplication extends Application
{
    public function getAuthorizerAccessToken(string $appId, string $refreshToken): string
    {
        $component_appid = $this->getAccount()->getAppId();
        $cacheKey = sprintf('open-platform.authorizer_access_token.%s.%s.%s', $component_appid, $appId, md5($refreshToken));

        /** @phpstan-ignore-next-line */
        $authorizerAccessToken = (string) $this->getCache()->get($cacheKey);

        if (! $authorizerAccessToken) {
            $response = $this->refreshAuthorizerToken($appId, $refreshToken);
            $authorizerAccessToken = (string) $response['authorizer_access_token'];
            $this->getCache()->set($cacheKey, $authorizerAccessToken, intval($response['expires_in'] ?? 7200) - 500);
        }

        return $authorizerAccessToken;
    }
}
