<?php

declare(strict_types=1);

namespace App\Filament\Pages\Concerns;

use Illuminate\Support\Facades\Cache;

trait CachesDberpReportAnalysisResults
{
    /**
     * @template T
     *
     * @param  callable(): T  $callback
     * @return T
     */
    protected function rememberReportAnalysis(string $reportKey, array $filters, callable $callback): mixed
    {
        $cacheSeconds = max(0, (int) config('dberp.report.analysis_cache_seconds', 60));

        if ($cacheSeconds <= 0) {
            return $callback();
        }

        $cacheKey = 'dberp.report.analysis.'.$reportKey.'.'.md5(json_encode($filters, JSON_THROW_ON_ERROR));

        return Cache::remember(
            $cacheKey,
            now()->addSeconds($cacheSeconds),
            $callback,
        );
    }
}
