<?php

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

uses(RefreshDatabase::class);

it('binds selected roles to a newly created permission', function () {
    // Create admin user with manage-settings permission via a role
    $admin = User::factory()->create();
    $role = Role::create(['name' => 'Admin', 'slug' => 'admin']);
    $admin->roles()->syncWithoutDetaching([$role->id]);

    // Grant manage-settings to the role so controller authorize passes
    $permManage = Permission::create(['name' => 'Manage Settings', 'slug' => 'manage-settings']);
    $role->permissions()->syncWithoutDetaching([$permManage->id]);

    // Create some roles to bind
    $r1 = Role::create(['name' => 'Editor', 'slug' => 'editor']);
    $r2 = Role::create(['name' => 'Viewer', 'slug' => 'viewer']);

    // Act
    $response = $this->actingAs($admin)
        ->post(route('admin.permissions.store'), [
            'name' => 'Export Data',
            'slug' => 'export-data',
            'description' => 'Can export data',
            'roles' => [$r1->id, $r2->id],
        ]);

    $response->assertRedirect();

    $permission = Permission::where('slug', 'export-data')->firstOrFail();
    expect($permission->roles()->pluck('slug')->sort()->values()->all())
        ->toEqualCanonicalizing(['editor', 'viewer']);
});
