<?php

namespace Database\Seeders;

use App\Enums\Permission as PermissionEnum;
use App\Enums\Role as RoleEnum;
use Illuminate\Database\Seeder;
use Spatie\Permission\Models\Permission;
use Spatie\Permission\Models\Role;
use Spatie\Permission\PermissionRegistrar;

class RolePermissionSeeder extends Seeder
{
    public function run(): void
    {
        $registrar = app(PermissionRegistrar::class);
        $registrar->forgetCachedPermissions();

        $permissions = collect(PermissionEnum::cases())
            ->mapWithKeys(fn (PermissionEnum $permission) => [
                $permission->value => Permission::findOrCreate($permission->value, 'web'),
            ]);

        $registrar->forgetCachedPermissions();

        foreach (RoleEnum::cases() as $role) {
            $roleModel = Role::findOrCreate($role->value, 'web');

            $roleModel->syncPermissions(
                collect($role->permissions())
                    ->map(fn (PermissionEnum $permission) => $permissions[$permission->value])
                    ->all()
            );
        }

        Role::query()
            ->where('guard_name', 'web')
            ->whereNotIn('name', RoleEnum::values())
            ->each(fn (Role $role) => $role->delete());

        Permission::query()
            ->where('guard_name', 'web')
            ->whereNotIn('name', PermissionEnum::values())
            ->each(fn (Permission $permission) => $permission->delete());

        $registrar->forgetCachedPermissions();
    }
}
