<?php

namespace Tests\Traits;

use App\Models\User;
use Spatie\Permission\Models\Permission;
use Spatie\Permission\Models\Role;

trait WithTestAuth
{
    protected function setUpTestAuth(): void
    {
        // Ensure roles exist
        Role::firstOrCreate(['name' => 'super_admin', 'guard_name' => 'web']);
        Role::firstOrCreate(['name' => 'panel_user', 'guard_name' => 'web']);
        Role::firstOrCreate(['name' => 'student', 'guard_name' => 'web']);
    }

    protected function createAdminUser(array $permissions = []): User
    {
        $this->setUpTestAuth();

        $user = User::factory()->create(['email' => 'admin_'.uniqid().'@test.com']);

        // For simple Admin Access, we often use super_admin in tests
        // But to test granular access, we can assign panel_user + specific permissions
        if (empty($permissions)) {
            $user->assignRole('super_admin');
        } else {
            $user->assignRole('panel_user'); // Access Panel

            // Create and assign granular permissions
            foreach ($permissions as $perm) {
                Permission::firstOrCreate(['name' => $perm, 'guard_name' => 'web']);
            }
            $user->givePermissionTo($permissions);
        }

        return $user;
    }

    protected function createStudentUser(): User
    {
        $this->setUpTestAuth();

        $user = User::factory()->create(['email' => 'student_'.uniqid().'@test.com']);

        // Students need 'student' role (logic logic) AND 'panel_user' (Shield Access)
        $user->assignRole('student');
        $user->assignRole('panel_user');

        return $user;
    }
}
