<?php
declare (strict_types = 1);

namespace app\openapi\controller\v1;

use OAuth2\OAuth2;
use OAuth2\OAuth2ServerException;
use oauth\OAuthStorage;
use Symfony\Component\HttpFoundation\Request;

class Authorize
{
    /**
     * 获取/刷新token
     */
    public function token()
    {
        try {
            $post = request()->post([
                'client_id',
                'client_secret',
                'grant_type',
                'refresh_token',
            ]);
            $server  = request()->server();
            $request = new Request([], $post, [], [], [], $server);
            $storage = new OAuthStorage;
            $oauth   = new OAuth2($storage, [
                'access_token_lifetime'  => intval(env('OPENAPI.ACCESS_TOKEN_LIFETIME', 3600)),
                'refresh_token_lifetime' => intval(env('OPENAPI.REFRESH_TOKEN_LIFETIME', 1209600)),
            ]);
            $token   = $oauth->grantAccessToken($request);
            return success('success', json_decode($token->getContent(), true));
        } catch (OAuth2ServerException $e) {
            return error($e->getMessage() . ' - ' . $e->getDescription());
        } catch (\Throwable $th) {
            return error($th->getMessage());
        }
    }
}