<?php

namespace Tests\Feature;

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

class RolePermissionManagementTest extends TestCase
{
    use RefreshDatabase;

    public function test_role_can_be_created_and_synced_with_permissions(): void
    {
        $admin = User::factory()->create(['status' => 'active']);
        $this->grantAdminRole($admin);
        $token = $admin->createToken('api-token')->plainTextToken;
        $permissions = Permission::query()->insert([
            ['name' => 'projects.view', 'display_name' => 'مشاهده پروژه‌ها', 'module' => 'projects', 'guard_name' => 'web', 'created_at' => now(), 'updated_at' => now()],
            ['name' => 'projects.edit', 'display_name' => 'ویرایش پروژه‌ها', 'module' => 'projects', 'guard_name' => 'web', 'created_at' => now(), 'updated_at' => now()],
        ]);

        $permissionIds = Permission::pluck('id')->all();

        $response = $this->withToken($token)
            ->postJson('/api/roles', [
                'name' => 'delivery_lead',
                'display_name' => 'راهبر تحویل',
                'description' => 'مدیریت تحویل پروژه‌ها',
                'permissions' => $permissionIds,
            ]);

        $response
            ->assertCreated()
            ->assertJsonPath('data.name', 'delivery_lead')
            ->assertJsonCount(2, 'data.permissions');

        $role = Role::where('name', 'delivery_lead')->firstOrFail();
        $this->assertCount(2, $role->permissions);
        $this->assertTrue($permissions);

        $this->withToken($token)
            ->postJson("/api/roles/{$role->id}/permissions", ['permissions' => [$permissionIds[0]]])
            ->assertOk()
            ->assertJsonCount(1, 'data.permissions');

        $this->assertSame([$permissionIds[0]], $role->fresh()->permissions()->pluck('permissions.id')->all());
    }

    public function test_user_roles_can_be_synced(): void
    {
        $admin = User::factory()->create(['status' => 'active']);
        $target = User::factory()->create(['status' => 'active']);
        $this->grantAdminRole($admin);
        $token = $admin->createToken('api-token')->plainTextToken;

        $roles = Role::query()->insert([
            ['name' => 'qa_observer', 'display_name' => 'ناظر کیفیت', 'guard_name' => 'web', 'created_at' => now(), 'updated_at' => now()],
            ['name' => 'delivery_manager', 'display_name' => 'مدیر تحویل', 'guard_name' => 'web', 'created_at' => now(), 'updated_at' => now()],
        ]);

        $roleIds = Role::whereIn('name', ['qa_observer', 'delivery_manager'])->pluck('id')->all();

        $this->withToken($token)
            ->putJson("/api/users/{$target->id}/roles", ['roles' => $roleIds])
            ->assertOk()
            ->assertJsonCount(2, 'data.roles');

        $this->assertSame($roleIds, $target->fresh()->roles()->pluck('roles.id')->all());
        $this->assertTrue($roles);
    }
}
