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

use function YOOtheme\app;
use YOOtheme\Http\Request;
use YOOtheme\Http\Response;
use ZOOlanders\YOOessentials\Api\Cloudflare\CloudflareApi;

class CloudflareAuthDriverController
{
    public const PRESAVE_API_TOKEN_ENDPOINT = 'yooessentials/auth/cloudflare/api-token';

    public function verifyApiToken(Request $request, Response $response)
    {
        $form = $request->getParam('auth') ?? [];
        $token = $form['accessToken'] ?? null;

        if (!$token) {
            return $response->withJson('Token must be specified.', 400);
        }

        try {
            $api = app(CloudflareApi::class);
            $tokenInfo = $api->verifyToken($token);
        } catch (\Exception $e) {
            return $response->withJson($e->getMessage(), 400);
        }

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