<?php

namespace App\Services;

use App\Models\FeatureFlag;
use Illuminate\Support\Facades\Cache;

class FeatureFlagService
{
    protected const CACHE_PREFIX = 'feature_flag:';
    protected const CACHE_TTL = 3600; // 1 hour

    /**
     * Check if a feature flag is enabled
     */
    public function isEnabled(string $key, ?int $userId = null): bool
    {
        return Cache::remember(
            self::CACHE_PREFIX . $key . ':' . ($userId ?? 'guest'),
            self::CACHE_TTL,
            function () use ($key, $userId) {
                $flag = FeatureFlag::where('key', $key)->first();
                
                if (!$flag) {
                    return false;
                }

                return $flag->isEnabledForUser($userId);
            }
        );
    }

    /**
     * Get all enabled feature flags for a user
     */
    public function getEnabledFlags(?int $userId = null): array
    {
        return Cache::remember(
            self::CACHE_PREFIX . 'all:' . ($userId ?? 'guest'),
            self::CACHE_TTL,
            function () use ($userId) {
                return FeatureFlag::where('is_enabled', true)
                    ->get()
                    ->filter(function ($flag) use ($userId) {
                        return $flag->isEnabledForUser($userId);
                    })
                    ->pluck('key')
                    ->toArray();
            }
        );
    }

    /**
     * Clear cache for a specific feature flag
     */
    public function clearCache(string $key): void
    {
        // Clear specific flag cache
        Cache::forget(self::CACHE_PREFIX . $key . ':guest');
        
        // Clear all flags cache
        $keys = Cache::get('feature_flag_keys', []);
        foreach ($keys as $cachedKey) {
            Cache::forget($cachedKey);
        }
        Cache::forget('feature_flag_keys');
    }

    /**
     * Clear all feature flag caches
     */
    public function clearAllCache(): void
    {
        Cache::flush(); // Or use a more targeted approach
    }

    /**
     * Enable a feature flag
     */
    public function enable(string $key): bool
    {
        $flag = FeatureFlag::where('key', $key)->first();
        
        if (!$flag) {
            return false;
        }

        $flag->update(['is_enabled' => true]);
        $this->clearCache($key);

        return true;
    }

    /**
     * Disable a feature flag
     */
    public function disable(string $key): bool
    {
        $flag = FeatureFlag::where('key', $key)->first();
        
        if (!$flag) {
            return false;
        }

        $flag->update(['is_enabled' => false]);
        $this->clearCache($key);

        return true;
    }
}

