<?php

namespace Tests\Feature;

use App\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Foundation\Testing\WithFaker;
use Symfony\Component\HttpFoundation\Response;
use Tests\TestCase;

class UserAuthTest extends TestCase
{
    use RefreshDatabase;

    /** @test */
    public function authentificated_user_can_be_fetched()
    {
        $this->withoutExceptionHandling();
        $this->actingAs($user = factory(User::class)->create(), 'api');

        $response = $this->get('/api/auth-user');

        $response->assertStatus(Response::HTTP_OK)
            ->assertJson([
                'data' => [
                    'user_id' => $user->id,
                    'attributes' => [
                        'name' => $user->name,
                    ]
                ],
                'links' => [
                    'self' => url('/users/'. $user->id),
                ]
            ]);
    }

    /** @test */
    public function an_admin_can_add_member()
    {
        $this->actingAs($user = factory(User::class)->create(['role' => 2]), 'api');

        $response = $this->post('/api/users', [
            'name' => 'TestName',
            'email' => 'test@test.fr',
        ])->assertStatus(Response::HTTP_CREATED);

        $this->assertCount(2, User::all());
    }

    /** @test */
    public function a_non_admin_cant_add_member()
    {
        $this->actingAs($user = factory(User::class)->create(), 'api');

        $response = $this->post('/api/users', [
            'name' => 'TestName',
            'email' => 'test@test.fr',
        ])->assertStatus(Response::HTTP_FORBIDDEN);

        $this->assertCount(1, User::all());
    }

    /** @test */
    public function an_admin_can_fetch_all_users()
    {
        $this->actingAs($user = factory(User::class)->create(['role' => 2]), 'api');
        $anotherUser = factory(User::class)->create();

        $response = $this->get('/api/users')->assertStatus(Response::HTTP_OK);

        $this->assertCount(2, User::all());
    }
}
