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

use YOOtheme\Http\Request;
use YOOtheme\Http\Response;
use ZOOlanders\YOOessentials\Api\Twitter\TwitterApiInterface;
use ZOOlanders\YOOessentials\Auth\AuthManager;
use ZOOlanders\YOOessentials\Data;

class TwitterAuthDriverController
{
    /**
     * @var string
     */
    public const PRE_SAVE_ENDPOINT = 'yooessentials/auth/twitter';

    public function presave(Request $request, Response $response, AuthManager $authManager, TwitterApiInterface $api)
    {
        $form = new Data($request->getParam('auth', []));
        $scopes = $form->scopes ?? $request('requiredScopes');

        try {
            if (!$form->refreshToken) {
                throw new \RuntimeException('No access has been granted.', 400);
            }

            /** @var TwitterAuthDriver $driver */
            $driver = $authManager->driver('twitter');

            $auth = $authManager
                ->initAuth($form->toArray())
                ->forDriver($driver)
                ->setScopes($scopes);

            $auth = $driver->renewToken($auth);

            $api->withAccessToken($auth->accessToken())->account();
        } catch (\Exception $e) {
            return $response->withJson($e->getMessage(), 400);
        }

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