<?php

namespace Velis\Test\Mvc\RestRequestHandler;

use Phalcon\Http\RequestInterface;
use PHPUnit\Framework\TestCase;
use Velis\App;
use Velis\Mvc\Controller\Exception\ForbiddenException;
use Velis\Mvc\Controller\RestRequestHandler\AbstractRestRequestHandler;
use Velis\Mvc\Controller\RestRequestHandler\VerifyCsrfToken;

class VerifyCsrfTokenTest extends TestCase
{
    /**
     * {@inheritDoc}
     */
    protected function setUp(): void
    {
        App::$session = App::$di['session'];
        App::$session->csrfToken = 'token';
    }

    public function testVerifyCsrfTokenSuccess()
    {
        $request = $this->createPartialMock(RequestInterface::class, []);
        $request->method('getMethod')->willReturn('POST');
        $request->method('getHeader')->willReturn('token')->with('X-CSRF-TOKEN');

        $nextHandler = $this->createPartialMock(VerifyCsrfToken::class, []);

        $verifyCsrfToken = new VerifyCsrfToken();
        $next = $verifyCsrfToken->setNext($nextHandler);

        $this->assertInstanceOf(AbstractRestRequestHandler::class, $next);

        $verifyCsrfToken->handle($request);
    }

    public function testVerifyCsrfTokenException()
    {
        $this->expectException(ForbiddenException::class);

        $request = $this->createPartialMock(RequestInterface::class, []);
        $request->method('getMethod')->willReturn('POST');
        $request->method('getHeader')->willReturn('different token')->with('X-CSRF-TOKEN');

        $verifyCsrfToken = new VerifyCsrfToken();

        $verifyCsrfToken->handle($request);
    }
}
