<?php

namespace App\Services\Traits;

use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Log;

trait RoleNameResolver
{
    public function getRoleName(int|string $roleId): string
    {
        $id = (int) $roleId;
        if ($id <= 0) {
            return (string) $roleId;
        }

        $cacheKey = "role_name:{$id}";
        $cachedName = Cache::get($cacheKey);
        if (is_string($cachedName) && $cachedName !== '') {
            return $cachedName;
        }

        try {
            $api = $this->getApi();
            if ($api && $api->online) {
                $roleBase = $api->getRoleBase($id);
                if (is_array($roleBase) && isset($roleBase['name']) && ! empty($roleBase['name'])) {
                    Cache::put($cacheKey, $roleBase['name'], now()->addMinutes(10));

                    return $roleBase['name'];
                }
            }
        } catch (\Exception $e) {
            Log::warning("Failed to get role name for {$id}: ".$e->getMessage());
        }

        return (string) $roleId;
    }
}
