<?php

namespace Tests\Feature\Api\Resources;

use Tests\TestCase;
use Illuminate\Foundation\Testing\DatabaseTransactions;
use App\User;
use App\Article;

class ArticleControllerTest extends TestCase
{
    use DatabaseTransactions;

    protected $adminToken;
    protected $factory;

    /**
    * A basic test example.
    *
    * @return void
    */
    public function setUp()
    {
       parent::setUp();
       $this->app->make(\Spatie\Permission\PermissionRegistrar::class)->registerPermissions();
       $admin = factory(User::class)->create();
       $admin->assignRole('Admin');
       $this->adminToken = \JWTAuth::fromUser($admin);
       $this->factory = factory(Article::class)->make()->toArray();
    }

    public function testGETAll()
    {
       $this->withHeaders([
               'Authorization' => 'Bearer '.$this->adminToken,
           ])
           ->json(
               'GET',
               '/api/articles'
           )
           ->assertStatus(200)
           ->assertHeader('Content-Type', 'application/json');
    }

    public function testPOST()
    {
        $factory = $this->factory;
        // $factory['password'] = 'secret';

        $response = $this->withHeaders([
                'Authorization' => 'Bearer '.$this->adminToken,
            ])
            ->json(
                'POST',
                '/api/articles',
                $factory
            )
            ->assertStatus(201)
            ->assertHeader('Content-Type', 'application/json');

        $json = json_decode($response->getContent());
        $factory['id'] = $json->id;

        $response->assertJson($factory);

        $this->assertDatabaseHas('articles', [
            'name' => $factory['name'],
        ]);
    }

    public function testDELETE()
    {
        $article = factory(Article::class)->create();

        $this->withHeaders([
                'Authorization' => 'Bearer '.$this->adminToken,
            ])
            ->json(
                'DELETE',
                '/api/articles/'.$article->id
            )
            ->assertStatus(204);

        $this->assertSoftDeleted('articles', [ 'name' => $article->name ]);
    }


    public function testDisallowAccessToGuestUser()
    {
        $this->json(
                'GET',
                '/api/articles'
            )
            ->assertStatus(401)
            ->assertHeader('Content-Type', 'application/json')
            ->assertJson([
                'message' => __('errors.unauthorized'),
                'message' => 'Token not provided',
            ]);
    }
}
