<?php

namespace AuthStack\SAMLServiceProvider\tests\units\Model;

use mageekguy\atoum;
use LightSaml\Helper;
use Illuminate\Http\Request;
use LightSaml\Model\Assertion\Issuer;
use LightSaml\Model\Protocol\LogoutRequest;
use LightSaml\Model\Context\SerializationContext;
use AuthStack\SAMLServiceProvider\Model\LogoutResponse;
use AuthStack\SAMLServiceProvider\Model\Logout as AuthstackLogout;

class Logout extends atoum
{
    public function testReceiveLogout()
    {
        $this
            ->given($logout_req = $this->getLogoutRequest())
            ->and($ctx = new SerializationContext())
            ->and($logout_req->serialize($ctx->getDocument(), $ctx))
            ->and($xml = $ctx->getDocument()->saveXML())
            ->and($request = new Request([
                'SAMLRequest' => base64_encode(gzdeflate($xml))], [], [], [], [], ['QUERY_STRING' => 'SAMLRequest=' . urlencode(base64_encode(gzdeflate($xml)))]))
            ->then
                ->object($logout_request = new AuthstackLogout())->isInstanceOf(AuthstackLogout::class)
                ->object($logout_request->receive($request))->isInstanceOf(AuthstackLogout::class)
                ->boolean($logout_request->validateLogoutRequest())->isTrue()
                ->object($resp = $logout_request->receive($request))->isInstanceof(AuthstackLogout::class)
                ->object($lightsaml_logout_resp = $resp->getLogoutResponse())->isInstanceOf(LogoutResponse::class);
        ;

    }


    protected function getLogoutRequest()
    {
        $request = new LogoutRequest();

        $request_id = Helper::generateID();

        $sp = new \AuthStack\SAMLServiceProvider\Model\ServiceProvider();
        $idp = new \AuthStack\SAMLServiceProvider\Model\IdentityProvider('https://authstack');

        $request
            ->setID($request_id)
            ->setDestination($idp->getLogoutURL())
            ->setIssueInstant(time())
            ->setIssuer(new Issuer($sp->getEntityId()))
        ;

        if($idp->wantsSignedReguests())
        {
            $request->setSignature($sp->getSignatureWriter());
        }

        return $request;
    }
}