<?php

namespace App\Http\Controllers\Api\V1\Identity;

use App\Domain\Identity\Enums\PermissionScope;
use App\Domain\Identity\Models\Role;
use App\Domain\Identity\Services\PermissionRegistry;
use App\Http\Controllers\Controller;
use App\Support\ApiResponse;
use Illuminate\Http\JsonResponse;
use Spatie\Permission\Models\Permission;

/**
 * Feeds the admin permission matrix: modules → permissions, plus the scopes a
 * grant may take.
 */
class PermissionController extends Controller
{
    public function index(): JsonResponse
    {
        $this->authorize('viewAny', Role::class);

        $stored = Permission::query()->get(['name', 'module', 'label'])->keyBy('name');

        $modules = [];
        foreach (PermissionRegistry::modules() as $module => $definition) {
            $permissions = [];

            foreach (array_keys($definition['permissions']) as $action) {
                $key = "{$module}.{$action}";

                if (! $stored->has($key)) {
                    continue; // Not yet synced into this environment.
                }

                $permissions[] = [
                    'name' => $key,
                    'action' => $action,
                    'label' => $stored[$key]->label,
                ];
            }

            $modules[] = [
                'module' => $module,
                'label' => $definition['label'],
                'permissions' => $permissions,
            ];
        }

        return ApiResponse::success([
            'modules' => $modules,
            'scopes' => array_map(fn (PermissionScope $scope) => [
                'value' => $scope->value,
                'label' => ucfirst($scope->value),
                'rank' => $scope->rank(),
            ], PermissionScope::cases()),
        ]);
    }
}
