<?php

namespace App\Console\Commands;

use App\Models\Category;
use App\Models\Permission;
use Illuminate\Console\Command;
use Illuminate\Support\Str;

class TestCommand extends Command
{
    protected $signature = 't';

    protected $description = 'Command description';

    public function handle(): void
    {
        Category::fixTree();
        dd();

        // Reset cached roles and permissions
        app()[\Spatie\Permission\PermissionRegistrar::class]->forgetCachedPermissions();



        // policy permissions
        $traitFunctions = array_merge(get_class_methods('Illuminate\Auth\Access\HandlesAuthorization'),
        /*            get_class_methods('App\Policies\HasPermissionTrait')*/);
        foreach ( new \DirectoryIterator(app_path('Policies')) as $fileinfo) {
            if (!$fileinfo->isDot()) {
                dd($fileinfo->getBasename('olicy.php'));
                $className = '\App\Policies\\'.$fileinfo->getBasename('.php');
                $reflectionClass = new \ReflectionClass($className);
                $methods = array_filter(
                    $reflectionClass->getMethods(),
                    function ($method) use ($className) {
//                        dd($method->getDeclaringClass()->getName(),$className);

                        return '\\'.$method->getDeclaringClass()->getName() === $className && $method->isPublic();
                    }
                );
                $policies = array_map(fn($m) => $m->getName(), $methods);
                $policies = array_diff($policies,$traitFunctions);


                foreach ($policies as $policy) {
//                    $tags = [];
//                    $annotate = $reflectionClass->getMethod($policy)->getDocComment();
//                    foreach (Str::of($annotate)->matchAll('/@\w+/') as $match)
//                        $tags[] = Str::remove('@',$match);

                    Permission::createOrFirst([
                        'group' => $fileinfo->getBasename('.php'),
                        'title' => $fileinfo->getBasename('.php'),
//                        'tag' => array_intersect($tags,['tenant','landlord']),
                        'name' => Str::kebab($fileinfo->getBasename('.php')).'.'.Str::kebab($policy).'.*',
                        'guard_name' => config('nova.guard','web')
                    ]);
                }
            }
        }


    }
}
