<?php

namespace App\Traits;

use Carbon\Carbon;
use Illuminate\Support\Facades\Cache;

trait CacheObject
{
    public static array $cache_values = [];

    protected function cache(string $key, int $lifetime, \Closure $closure, string $tag = null)
    {
        $cacheInstance = $tag ? Cache::tags(tenant('id') . '-' . $tag) : Cache::store();
        $full_key = tenant('id') . '-' . $key;
        if (isset(self::$cache_values[$full_key]) && app()->environment('production')) {
            return self::$cache_values[$full_key]();
        }

        self::$cache_values[$full_key] = $closure;

        return $cacheInstance->remember($full_key, $this->cacheLife($lifetime), self::$cache_values[$full_key]);
    }

    public function clearCache(string $key): void
    {
        $full_key = tenant('id') . '-' . $key;
        Cache::forget($full_key);
        if (isset(self::$cache_values[$full_key])) {
            unset(self::$cache_values[$full_key]);
        }
    }

    private function cacheLife(int $lifetime): Carbon
    {
        return Carbon::now()->addMinutes(app()->environment('production') ? $lifetime : 0);
    }
}
