<?php

namespace Tests\Feature\Role;

use App\Models\Permission;
use App\Models\Role;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Foundation\Testing\WithFaker;
use Tests\TestCase;

class DeleteTest extends TestCase
{
    use RefreshDatabase, WithFaker;

    public function test_guest_cannot_view_role(): void
    {
        $role = Role::factory()->create();
        $response = $this->postJson(route('roles.destroy', [$role->id]));

        $response->assertUnauthorized();
    }

    public function test_a_role_can_be_deleted()
    {
        $user = User::factory()->create();
        $role = Role::factory()->create();

        $permission = Permission::factory([
            'id' => 2,
            'name' => $this->faker->name
        ])->create();

        $role->syncPermissions($permission);

        $this->assertDatabaseHas('roles', [
            'id' => $role->id,
            'name' => $role->name,
            'name_fa' => $role->name_fa,
        ]);

        $this->assertDatabaseHas('role_has_permissions', [
            'permission_id' => $permission->id,
            'role_id' => $role->id
        ]);

        $response = $this->actingAs($user)->deleteJson(route('roles.destroy', [$role->id]));

        $response->assertOk()
            ->assertExactJson([
                'message' => __('messages.successful')
            ]);

        $this->assertDatabaseMissing('roles', [
            'id' => $role->id,
            'name' => $role->name,
            'name_fa' => $role->name_fa,
        ]);

        $this->assertDatabaseMissing('role_has_permissions', [
            'permission_id' => $permission->id,
            'role_id' => $role->id
        ]);
    }
}
