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

use YOOtheme\Config;
use YOOtheme\Http\Request;
use YOOtheme\Http\Response;
use ZOOlanders\YOOessentials\HttpClientInterface;

class AuthController
{
    public const GENERATE_ID_ENDPOINT = 'yooessentials/auth/generate-id';
    public const POLL_ENDPOINT = 'yooessentials/auth/poll';

    public function generateId(Request $request, Response $response, Config $config)
    {
        $prefix = $request->getParam('driver', '');

        return $response->withJson([
            'id' => md5(uniqid($prefix . '-') . $config->get('app.secret')),
        ]);
    }

    public function poll(Request $request, Response $response, HttpClientInterface $client, AuthManager $manager)
    {
        $driverName = $request->getParam('driver');
        $driver = $manager->driver($driverName);

        $url = $driver->endpoint('poll');

        $query = http_build_query(['id' => $request->getParam('id'), 'scopes' => $request->getParam('scopes')]);

        /** @var Response $responseFromAuth */
        $responseFromAuth = $client->get($url . '?' . $query);

        return $response->withJson(json_decode((string) $responseFromAuth->getBody(), true));
    }
}
