<?php

namespace App\Framework\Cache;

use ReflectionException;
use ReflectionMethod;

final readonly class CacheDecorator
{
    public function __construct(
        private object $service,
        private Cache  $cache
    ) {}

    /**
     * @throws ReflectionException
     */
    public function __call(string $name, array $args)
    {
        $method = new ReflectionMethod($this->service, $name);
        $attrs = $method->getAttributes(Cacheable::class);

        if ($attrs) {
            $attr = $attrs[0]->newInstance();
            $key = $attr->key ?? $method->getName() . ':' . md5(serialize($args));
            $ttl = $attr->ttl ?? 3600;
            return $this->cache->remember($key, fn() => $method->invokeArgs($this->service, $args), $ttl);
        }

        return $method->invokeArgs($this->service, $args);
    }
}
