<?php

namespace App\Services;

use Spatie\Permission\Models\Permission;
use Illuminate\Database\Eloquent\Collection;

class PermissionService
{
    protected LoggingService $loggingService;

    public function __construct(LoggingService $loggingService)
    {
        $this->loggingService = $loggingService;
    }

    public function getAllPermissions(): Collection
    {
        $this->loggingService->logService('PermissionService::getAllPermissions');
        return Permission::where('guard_name', 'sanctum')->get();
    }

    public function getPermissionsByModule(): array
    {
        $this->loggingService->logService('PermissionService::getPermissionsByModule');

        $permissions = Permission::where('guard_name', 'sanctum')->get();

        $grouped = [];
        foreach ($permissions as $permission) {
            $parts = explode('.', $permission->name);
            $module = $parts[0];
            $action = $parts[1] ?? $permission->name;

            if (!isset($grouped[$module])) {
                $grouped[$module] = [];
            }

            $grouped[$module][] = [
                'id' => $permission->id,
                'name' => $permission->name,
                'action' => $action,
            ];
        }

        return $grouped;
    }

    public function getPermission(int $id): Permission
    {
        $this->loggingService->logService('PermissionService::getPermission', ['id' => $id]);
        return Permission::findOrFail($id);
    }
}
