<?php

namespace Database\Seeders;

use App\Models\InternalUser;
use App\Models\PermissionGroup;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\Artisan;
use App\Models\Permission;
use Spatie\Permission\Models\Role;


class PermissionsTableSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        Artisan::call('cache:forget spatie.permission.cache');

        $aclGroups = config('acl.group-permissions');
        $permissionsToInsert = [];

        $groups = collect($aclGroups)
            ->keys()
            ->map(fn($group) => [
                'name' => $group,
            ])
            ->toArray();

        PermissionGroup::insertOrIgnore($groups);

        PermissionGroup::select('id', 'name')
            ->with('permissions')
            ->latest('id')
            ->cursor()
            ->each(function ($permissionGroup) use ($aclGroups, &$permissionsToInsert) {
                if(!isset($aclGroups[$permissionGroup->name])){
                   return true;
                }
                $permissionsToInsert = collect($aclGroups[$permissionGroup->name])
                    ->diff($permissionGroup->permissions ?  $permissionGroup->permissions->pluck('name')->flatten()->toArray() : [])
                    ->map(function ($permissionName) use ($permissionGroup) {
                        return [
                            'name' => $permissionName,
                            'guard_name' => 'web',
                            'permission_group_id' => $permissionGroup->id,
                        ];
                    })
                    ->concat($permissionsToInsert)
                    ->all();
            });

        if (count($permissionsToInsert) == 0) {
            $this->command->info('No Permissions to insert');
            return;
        }

        Permission::insertOrIgnore($permissionsToInsert);

        $role = Role::query()->firstOrCreate(['name' => 'super-admin']);
        $role->syncPermissions(Permission::query()->get());

        $user = InternalUser::query()->where('phone_number','=','966512345678')->first();
        $user->assignRole('super-admin');
        $this->command->info('Permissions Inserted');

    }
}

