<?php

namespace KupShop\ApiBundle\View;

use KupShop\ApiBundle\Api\Errors;
use KupShop\KupShopBundle\Context\DomainContext;
use KupShop\KupShopBundle\Util\Contexts;
use KupShop\KupShopBundle\Views\View;
use Luracast\Restler\Defaults;
use Luracast\Restler\Explorer\Info;
use Luracast\Restler\Explorer\v1\Explorer;
use Luracast\Restler\Restler;
use Psr\Log\LoggerInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;

class ApiView extends View
{
    private LoggerInterface $logger;

    public $requirements = [
        'modules' => [
            'eshop_users' => true,
            'api' => true,
        ],
        'logged_user' => true,
    ];

    public function __construct(LoggerInterface $logger)
    {
        $this->logger = $logger;
    }

    public function getResponse(?Request $request = null)
    {
        // MRTĚ HUSTO KRUTOPŘÍSNEJ JOEŮV HACK:
        $_SERVER['SCRIPT_NAME'] = '/api/launch.php';

        Explorer::$hideProtected = false;
        Explorer::$allowScalarValueOnRequestBody = false;

        global $cfg;
        Defaults::$useUrlBasedVersioning = true;
        Defaults::$cacheDirectory = realpath($cfg['Path']['data'].'tmp/cache');
        Defaults::$crossOriginResourceSharing = true;
        Defaults::$accessControlAllowOrigin = '*';
        Defaults::$returnResponse = true;
        Defaults::$apiAccessLevel = 2;

        $r = new Restler(!isDevelopment());
        $r->onComplete(function () use ($r) {
            Errors::log($this->logger, $r);
        });

        $r->addErrorClass(Errors::class);

        Info::$contactEmail = 'wpj@wpj.cz';
        Info::$description = 'Live B2B API Documentation';
        Info::$title = 'B2B API Documentation';

        $r->setAPIVersion(1);
        $r->addAPIClass('KupShop\ApiBundle\Api\Endpoints\CartEndpoint', 'cart');
        $r->addAPIClass('KupShop\ApiBundle\Api\Endpoints\OrderEndpoint', 'order');
        $r->addAPIClass('KupShop\ApiBundle\Api\ApiExplorer', 'explorer');
        $r->setSupportedFormats('JsonFormat', 'XmlFormat');
        $r->addAuthenticationClass('KupShop\ApiBundle\Api\Auth');
        $r->setBaseUrls('https://'.Contexts::get(DomainContext::class)->getActiveId());
        $response = new Response($r->handle(), $r->responseCode);
        $response->headers->set('Content-Type', $r->responseFormat->getMIME());

        return $response;
    }
}
