<?php

/**
 * Copyright (c) 2019. CDEK-IT. All rights reserved.
 * See LICENSE.md for license details.
 *
 * @author Chizhekov Viktor
 */

namespace CdekSDK2\Tests;

use CdekSDK2\Constants;
use CdekSDK2\Exceptions\AuthException;
use CdekSDK2\Http\Api;
use Http\Mock\Client;
use Nyholm\Psr7\Response;
use PHPUnit\Framework\TestCase;

class ApiTest extends TestCase
{
    /**
     * @var Api
     */
    protected $api;

    protected function setUp(): void
    {
        parent::setUp();
        $responsePSR7 = new Response(200, [], '{"uuid": "c7e28f79fe39"}');
        $client = $this->createMock(Client::class);
        $client->method('sendRequest')->willReturn($responsePSR7);

        $this->api = new Api($client, Constants::TEST_ACCOUNT, Constants::TEST_SECURE);
    }

    protected function tearDown(): void
    {
        parent::tearDown(); // TODO: Change the autogenerated stub
        $this->api = null;
    }

    public function testConstruct()
    {
        $api = new Api(new Client());
        $this->assertInstanceOf(Api::class, $api);
    }

    public function testGet()
    {
        $response = $this->api->get('/custom-url');
        $this->assertEquals(200, $response->getStatus());
    }

    public function testPost()
    {
        $response = $this->api->post('someurl', []);
        $this->assertEquals(200, $response->getStatus());
    }

    public function testDelete()
    {
        $response = $this->api->delete('someurl');
        $this->assertEquals(200, $response->getStatus());
    }

    public function testSetTest()
    {
        $this->api->setTest(true);
        $this->assertTrue($this->api->isTest());
        $this->assertStringContainsString(Constants::TEST_ACCOUNT, $this->api->getAccount());
        $this->assertStringContainsString(Constants::TEST_SECURE, $this->api->getSecure());
    }

    public function testAuthorize()
    {
        $responsePSR7 = new Response(401, [], '{"error": "not authorize"}');
        $client = $this->createMock(Client::class);
        $client->method('sendRequest')->willReturn($responsePSR7);

        $api = new Api($client);
        $api->setSecure('invalid-data');
        $this->expectException(AuthException::class);
        $api->authorize();
    }
}
