<?php

namespace Tests\Feature;

use App\Models\User;
use Database\Seeders\PermissionSeeder;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Spatie\Permission\Models\Role;
use Tests\TestCase;

class SpatiePermissionTest extends TestCase
{
    use RefreshDatabase;

    protected function setUp(): void
    {
        parent::setUp();

        // Seed roles and permissions before each test
        $this->seed(PermissionSeeder::class);
    }

    public function test_super_admin_can_access_dashboard_and_users_list(): void
    {
        $superAdmin = User::factory()->create(['role' => 'admin']);
        $superAdmin->assignRole('Super Admin');

        $this->actingAs($superAdmin)
            ->get(route('admin.dashboard'))
            ->assertOk();

        $this->actingAs($superAdmin)
            ->get(route('admin.users.index'))
            ->assertOk();
    }

    public function test_staff_cannot_access_users_management(): void
    {
        $staffUser = User::factory()->create(['role' => 'admin']);
        $staffUser->assignRole('Staff');

        // Staff has dashboard.view permission, so they can open the dashboard
        $this->actingAs($staffUser)
            ->get(route('admin.dashboard'))
            ->assertOk();

        // Staff does NOT have users.view permission, so users index should return 403 Forbidden
        $this->actingAs($staffUser)
            ->get(route('admin.users.index'))
            ->assertStatus(403);
    }

    public function test_staff_can_access_products_list(): void
    {
        $staffUser = User::factory()->create(['role' => 'admin']);
        $staffUser->assignRole('Staff');

        // Staff has products.view permission
        $this->actingAs($staffUser)
            ->get(route('admin.products.index'))
            ->assertOk();
    }

    public function test_staff_cannot_edit_settings(): void
    {
        $staffUser = User::factory()->create(['role' => 'admin']);
        $staffUser->assignRole('Staff');

        // Staff only has settings.view, NOT settings.update
        $this->actingAs($staffUser)
            ->put(route('admin.settings.update'), [
                'site_name' => 'Hack Attempt'
            ])
            ->assertStatus(403);
    }
}
