<?php

namespace App\Services\Admin\Developer;

use App\Support\PermissionCatalog;
use Illuminate\Support\Collection;
use Spatie\Permission\Models\Role;
use Spatie\Permission\PermissionRegistrar;

class RolePermissionService
{
    /**
     * @return array<string, array<int, string>>
     */
    public function groupedPermissions(): array
    {
        return PermissionCatalog::groups();
    }

    /**
     * @return Collection<int, array{id: int, name: string, permissions: array<int, string>}>
     */
    public function roles(): Collection
    {
        return Role::with('permissions:id,name')
            ->orderBy('name')
            ->get(['id', 'name'])
            ->map(fn (Role $role) => [
                'id' => $role->id,
                'name' => $role->name,
                'permissions' => $role->permissions->pluck('name')->all(),
            ]);
    }

    /**
     * @param  array<int, string>  $permissionNames
     */
    public function updatePermissions(Role $role, array $permissionNames): Role
    {
        $valid = array_values(array_intersect($permissionNames, PermissionCatalog::all()));

        if ($role->name === 'developer') {
            $valid = array_values(array_unique([...$valid, 'view-roles', 'update-roles']));
        }

        $role->syncPermissions($valid);

        app(PermissionRegistrar::class)->forgetCachedPermissions();

        return $role->load('permissions:id,name');
    }
}
