<?php
/**
 * @package   Essentials YOOtheme Pro 2.2.16 build 0813.1608
 * @author    ZOOlanders https://www.zoolanders.com
 * @copyright Copyright (C) Joolanders, SL
 * @license   http://www.gnu.org/licenses/gpl.html GNU/GPL
 */

namespace ZOOlanders\YOOessentials\Auth\Driver\Google;

use function YOOtheme\app;
use ZOOlanders\YOOessentials\HttpClientInterface;
use ZOOlanders\YOOessentials\Auth\AuthDriver;
use ZOOlanders\YOOessentials\Auth\AuthOAuth;
use ZOOlanders\YOOessentials\Auth\RenewTokenInterface;

class GoogleAuthDriver extends AuthDriver implements RenewTokenInterface
{
    public const CLIENT_ID = '1084661277420-9jleq1k3bmam11ibd7sq6figa0phabi1.apps.googleusercontent.com';
    public const CLIENT_SECRET = 'Tl6XAv0vw9NHq3CXT_uda5Kp';

    public function renewToken(AuthOAuth $auth): AuthOAuth
    {
        /** @var HttpClientInterface $client */
        $client = app(HttpClientInterface::class);

        $clientId = self::CLIENT_ID;
        $clientSecret = self::CLIENT_SECRET;

        if ($auth->custom()) {
            $clientId = $auth->clientId();
            $clientSecret = $auth->clientSecret();
        }

        $response = $client->post(
            'https://oauth2.googleapis.com/token',
            [
                'grant_type' => 'refresh_token',
                'client_id' => $clientId,
                'client_secret' => $clientSecret,
                'refresh_token' => $auth->refreshToken(),
            ],
            [
                'Content-Type' => 'application/x-www-form-urlencoded',
            ]
        );

        $result = json_decode($response->getBody(), true);

        return $auth->setAccessToken($result['access_token'] ?? '')->setExpiresIn($result['expires_in'] ?? 0);
    }

    public function tokenScopes(AuthOAuth  $auth): array
    {
        /** @var HttpClientInterface $client */
        $client = app(HttpClientInterface::class);

        $response = $client->post(
            'https://www.googleapis.com/oauth2/v1/tokeninfo',
            [
                'access_token' => $auth->accessToken(),
            ],
        );

        $result = json_decode($response->getBody(), true);
        $scopes = explode(' ', $result['scope'] ?? '');
        if (!$scopes) {
            return [];
        }

        $auth->setScopes($scopes);

        return $scopes;
    }
}
