<?php

namespace App\Services\Admin\ProductConfigOption;

use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;

class UsageStatsService
{
    private const CACHE_TTL = 300;

    public function calculate(int $optionId): array
    {
        return Cache::remember($this->cacheKey($optionId), self::CACHE_TTL, function () use ($optionId) {
            return [
                'products_count' => DB::table('product_config_option_relations')
                    ->where('option_id', $optionId)
                    ->distinct('product_id')->count('product_id'),
                'client_products_count' => DB::table('client_product_config_option_values')
                    ->where('option_id', $optionId)
                    ->distinct('product_id')->count('product_id'),
            ];
        });
    }

    public function invalidate(int $optionId): void
    {
        Cache::forget($this->cacheKey($optionId));
    }

    private function cacheKey(int $optionId): string
    {
        return "option_usage_{$optionId}";
    }
}
