<?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 YOOtheme\Http\Request;
use YOOtheme\Http\Response;
use ZOOlanders\YOOessentials\Auth\AuthOAuth;

class TikTokAuthDriverController
{
    /**
     * @var string
     */
    public const PRE_SAVE_ENDPOINT = 'yooessentials/auth/tiktok';

    public function presave(Request $request, Response $response)
    {
        $auth = $request->getParam('auth', []);
        $refreshToken = $auth['refreshToken'] ?? null;

        if (!$refreshToken) {
            return $response->withJson('Missing Refresh Token or no access has been granted.', 400);
        }

        try {
            $driver = new TikTokAuthDriver();
            $data = $driver->renewToken(new AuthOAuth($auth))->toArray();

            $auth = array_merge($auth, [
                'scopes' => $data['scopes'],
                'accessToken' => $data['accessToken'],
                'refreshToken' => $data['refreshToken'],
                'expiresAt' => $data['expiresAt']
            ]);
        } catch (\Exception $e) {
            return $response->withJson($e->getMessage(), 400);
        }

        return $response->withJson($auth, 200);
    }
}
