<?php

namespace Tests\Feature\Api\Authorization;

use Facades\Tests\Setup\UserFactory;
use Tests\Feature\ApiTestCase;
use App\Http\Resources\PermissionResource;
use App\Models\Permission;
use App\Models\User;

class PermissionsControllerTest extends ApiTestCase
{
    
    public function test_unauthenticated()
    {
        $this->getJson('/api/permissions')->assertStatus(401);
    }

    
    public function test_get_users_without_permission()
    {
        $user = User::factory()->create();

        $this->actingAs($user, self::API_GUARD)
            ->getJson('/api/permissions')
            ->assertForbidden();
    }

    
    public function test_get_permissions()
    {
        Permission::factory()->times(3)->create();

        $response = $this->actingAs($this->getUser(), self::API_GUARD)
            ->getJson('/api/permissions')
            ->assertOk();

        // 7 default permissions + 3 newly created
        $this->assertCount(10, $response->original);
    }

    
    public function test_get_permission()
    {
        $permission = Permission::factory()->create();

        $this->actingAs($this->getUser(), self::API_GUARD)
            ->getJson("/api/permissions/{$permission->id}")
            ->assertOk()
            ->assertJson([
                'data' => (new PermissionResource($permission))->toArray(request()),
            ]);
    }

    
    public function test_create_permission()
    {
        $data = [
            'name' => 'foo',
            'display_name' => 'Foo Permission',
            'description' => 'This is foo permission.',
        ];

        $this->actingAs($this->getUser(), self::API_GUARD)
            ->postJson('/api/permissions', $data)
            ->assertStatus(201)
            ->assertJsonFragment($data);

        $this->assertDatabaseHas('permissions', $data);
    }

    
    public function test_create_permission_with_invalid_name()
    {
        $this->actingAs($this->getUser(), self::API_GUARD)
            ->postJson('/api/permissions')
            ->assertStatus(422)
            ->assertJsonValidationErrors('name');

        $existingPermission = Permission::first();

        $this->postJson('/api/permissions', ['name' => $existingPermission->name])
            ->assertStatus(422)
            ->assertJsonValidationErrors('name');

        $this->postJson('/api/permissions', ['name' => 'foo bar'])
            ->assertStatus(422)
            ->assertJsonValidationErrors('name');
    }

    
    public function test_partially_update_permission()
    {
        $this->getUser();

        $permission = Permission::factory()->create();

        $data = ['name' => 'foo'];
        $expected = $data + ['id' => $permission->id];

        $this->actingAs($this->getUser(), self::API_GUARD)
            ->patchJson("/api/permissions/{$permission->id}", $data)
            ->assertJsonFragment($expected);

        $this->assertDatabaseHas('permissions', $expected);
    }

    
    public function test_update_permission()
    {
        $permission = Permission::factory()->create();

        $data = [
            'name' => 'foo',
            'display_name' => 'Foo Role',
            'description' => 'This is foo role.',
        ];
        $expected = $data + ['id' => $permission->id];

        $this->actingAs($this->getUser(), self::API_GUARD)
            ->patchJson("/api/permissions/{$permission->id}", $data)
            ->assertJsonFragment($expected);

        $this->assertDatabaseHas('permissions', $expected);
    }

    
    public function test_remove_permission()
    {
        $permission = Permission::factory()->create(['removable' => true]);

        $this->actingAs($this->getUser(), self::API_GUARD)
            ->deleteJson("/api/permissions/{$permission->id}")
            ->assertOk()
            ->assertJson(['success' => true]);

        $this->assertDatabaseMissing('permissions', ['id' => $permission->id]);
    }

    
    public function test_remove_non_removable_permission()
    {
        $permission = Permission::factory()->create(['removable' => false]);

        $this->actingAs($this->getUser(), self::API_GUARD)
            ->deleteJson("/api/permissions/{$permission->id}")
            ->assertStatus(403);
    }

    /**
     * @return mixed
     */
    private function getUser()
    {
        return UserFactory::user()->withPermissions('permissions.manage')->create();
    }
}
