<?php

namespace App\Services;

use App\Contracts\AuditLogServiceInterface;
use App\Contracts\PermissionRepositoryInterface;
use App\Models\Role;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Support\Facades\Auth;

class PermissionService
{
    public function __construct(
        protected PermissionRepositoryInterface $permissionRepository,
        protected AuditLogServiceInterface $auditLogService
    ) {}

    public function getPermissionsGroupedByModule(): array
    {
        return $this->permissionRepository->getAllPermissionsGroupedByModule();
    }

    public function getRolesWithPermissions(): Collection
    {
        return $this->permissionRepository->getAllRolesWithPermissions();
    }

    public function updateRolePermissions(int $roleId, array $permissionIds): bool
    {
        $role = Role::findOrFail($roleId);
        $updated = $this->permissionRepository->updateRolePermissions($roleId, $permissionIds);

        if ($updated) {
            $user = Auth::user();
            $this->auditLogService->log(
                $user,
                'ROLE_PERMISSIONS_UPDATED',
                "Memperbarui matriks hak akses permission untuk peran: {$role->label}"
            );
        }

        return $updated;
    }
}
