<?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\TikTok;

use function YOOtheme\app;
use ZOOlanders\YOOessentials\Api\TikTok\TikTokApi;
use ZOOlanders\YOOessentials\Api\TikTok\TikTokApiInterface;
use ZOOlanders\YOOessentials\Auth\AuthDriver;
use ZOOlanders\YOOessentials\Auth\AuthOAuth;
use ZOOlanders\YOOessentials\Auth\RenewTokenInterface;

class TikTokAuthDriver extends AuthDriver implements RenewTokenInterface
{
    protected const CLIENT_KEY = 'aw7gb56h2gkhl8a9';
    protected const CLIENT_SECRET = 'f41aee5ad1a58bf962828c71c9f13ed3';

    public function renewToken(AuthOAuth $auth): AuthOAuth
    {
        /** @var TikTokApi $api */
        $api = app(TikTokApiInterface::class);

        try {
            $data = $api->refreshAccessToken(
                $auth->refreshToken(),
                self::CLIENT_KEY,
                self::CLIENT_SECRET
            );
        } catch (\Exception $e) {
            return $auth;
        }

        if (!isset($data['access_token'], $data['refresh_token'], $data['expires_in'])) {
            return $auth;
        }

        return $auth
            ->setAccessToken($data['access_token'])
            ->setRefreshToken($data['refresh_token'])
            ->setExpiresIn($data['expires_in']);
    }
}
