<?php
namespace Misuzu\Twitter;

use Index\Routing\IRouter;
use Misuzu\MisuzuContext;
use Misuzu\Config\IConfig;
use Misuzu\Twitter\TwitterAccessToken;
use Misuzu\Twitter\TwitterAuthorisation;
use Misuzu\Twitter\TwitterClient;
use Misuzu\Twitter\TwitterClientId;

final class TwitterRoutes {
    private MisuzuContext $context;
    private IConfig $config;
    private ?TwitterClientId $clientId = null;

    public function __construct(MisuzuContext $ctx, IRouter $router, IConfig $config) {
        $this->context = $ctx;
        $this->config = $config;

        $router->get('/_twitter/callback', [$this, 'callback']);
    }

    private function getClientId(): TwitterClientId {
        if($this->clientId === null)
            $this->clientId = TwitterClientId::load($this->config->scopeTo('oauth2'));
        return $this->clientId;
    }

    public function callback($response, $request) {
        $qState = (string)$request->getParam('state');
        $qCode = (string)$request->getParam('code');
        $cVerifier = (string)$request->getCookie('msz_twitter');

        if(empty($qState) || empty($qCode) || empty($cVerifier))
            return 400;

        $response->removeCookie('msz_twitter', '/', msz_cookie_domain(), !empty($_SERVER['HTTPS']), true);

        $clientId = $this->getClientId();
        if(!TwitterAuthorisation::verifyState($clientId, $qState))
            return 403;

        $accessToken = TwitterAccessToken::empty();
        $client = new TwitterClient($clientId, $accessToken);

        $redirect = url_prefix(false) . url('twitter-callback');
        $tokenInfo = TwitterAccessToken::fromTwitterResponse($client->token($qCode, $cVerifier, $redirect));
        TwitterAccessToken::save($this->config->scopeTo('access'), $tokenInfo);

        $response->redirect(url('manage-general-twitter'));
    }
}
