<?php

namespace App\Helpers;

use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Redis;
use App\Helpers\AuthHelper;
use Illuminate\Support\Facades\Auth;

class CacheHelper
{
    public static function userId(): ?string
    {
        $user = Auth::user();
        if (!$user) {
            return null;
        }

        return $user->role === 'super_admin'
            ? (string) $user->id
            : (string) $user->franchisee_id;
    }
    public static function franchiseeId(): ?string
    {
        $user = Auth::user();
        if (!$user) {
            return null;
        }

        return $user->role === 'super_admin'
            ? null
            : $user->franchisee_id;
    }

    public static function isSuperAdmin(): bool
    {
        $user = Auth::user();
        return $user && $user->role === 'super_admin';
    }

    public static function remember($key, \Closure $callback)
    {
        $userId = self::userId();
        $tags = "franchisee_{$userId}";

        if (!is_array($tags)) {
            $tags = [$tags];
        }
        // 🔹 Remember for 60 minutes (3600s)
        return Cache::store('redis')
            ->tags($tags)
            ->remember($key, 3600, $callback);
    }
    public static function rememberByTag($tag, $key, \Closure $callback)
    {
        $franchiseId = self::franchiseeId() ?? 'global';

        return Cache::store('redis')
            ->tags([$tag, "franchisee_{$franchiseId}"])
            ->remember($key, 3600, $callback);
    }
    /**
     * Remember data in Redis store.
     */
    // public static function remember($key, $seconds, \Closure $callback)
    // {
    //     return Cache::remember($key, $seconds, $callback);
    // }

    /**
     * Forget a specific Redis key.
     */
    public static function forget($key)
    {
        $userId = self::userId();
        $tag = "franchisee_{$userId}";
        Cache::tags([$tag])->forget($key);
    }
    public static function forgetByTag($tag)
    {
        $franchiseId = self::franchiseeId() ?? 'global';

        Cache::store('redis')
            ->tags([$tag, "franchisee_{$franchiseId}"])
            ->flush();
    }

    /**
     * Flush every Redis cache entry for a tag (all franchise scopes).
     */
    public static function flushRedisTag(string $tag): void
    {
        Cache::store('redis')->tags([$tag])->flush();
    }

    /**
     * Flush Redis cache for one or more tags (used by rememberByTag on redis).
     *
     * @param string|array $tags
     */
    public static function clearByTag($tags): bool
    {
        try {
            $tagList = is_array($tags) ? $tags : [$tags];
            Cache::store('redis')->tags($tagList)->flush();

            \Log::info('✅ Redis cache cleared for tags: ' . implode(', ', $tagList));

            return true;
        } catch (\Throwable $e) {
            \Log::error('❌ Failed to clear Redis cache by tag: ' . $e->getMessage());
            return false;
        }
    }

    /**
     * Flush all Redis cache .
     *
     * @param string|array $tags
     * @return bool
     */
    public static function clearAllCache(): bool
    {
        try {
            Cache::store('redis')->getRedis()->flushAll();

            \Log::info('✅ Redis all cache cleared');

            return true;
        } catch (\Throwable $e) {
            \Log::error('❌ Failed to clear all Redis cache' . $e->getMessage());
            return false;
        }
    }

}
