<?php

namespace App\Services;

use App\Models\Product;
use Illuminate\Support\Facades\Cache;

class CacheService
{
    /**
     * Cache keys used throughout the application
     */
    public const HOMEPAGE_FEATURED_PRODUCTS = 'homepage.featured_products';
    public const HOMEPAGE_CATEGORIES = 'homepage.categories';
    public const HOMEPAGE_BANNERS = 'homepage.banners';
    public const HOMEPAGE_BEST_SELLERS = 'homepage.best_sellers';
    public const HOMEPAGE_NEW_ARRIVALS = 'homepage.new_arrivals';
    public const HOMEPAGE_ON_SALE = 'homepage.on_sale';
    public const HOMEPAGE_CATEGORY_WISE_PRODUCTS = 'homepage.category_wise_products';

    /**
     * Clear all homepage cache
     */
    public function clearHomepageCache(): void
    {
        Cache::forget(self::HOMEPAGE_FEATURED_PRODUCTS);
        Cache::forget(self::HOMEPAGE_CATEGORIES);
        Cache::forget(self::HOMEPAGE_BANNERS);
        Cache::forget(self::HOMEPAGE_BEST_SELLERS);
        Cache::forget(self::HOMEPAGE_NEW_ARRIVALS);
        Cache::forget(self::HOMEPAGE_ON_SALE);
        Cache::forget(self::HOMEPAGE_CATEGORY_WISE_PRODUCTS);
    }

    /**
     * Clear product-related cache
     */
    public function clearProductCache(): void
    {
        $this->clearHomepageCache();
    }

    /**
     * Clear product detail and related listing caches for a specific product.
     */
    public function clearProductDetailCache(Product $product): void
    {
        Cache::forget('product_detail_' . $product->slug);
        Cache::forget('product_related_' . $product->id);
        Cache::forget('product_recent_' . $product->id);

        if ($product->parent_id) {
            $parent = Product::find($product->parent_id);
            if ($parent) {
                Cache::forget('product_detail_' . $parent->slug);
            }
        }
    }

    /**
     * Clear category-related cache
     */
    public function clearCategoryCache(): void
    {
        Cache::forget(self::HOMEPAGE_CATEGORIES);
        Cache::forget(self::HOMEPAGE_CATEGORY_WISE_PRODUCTS);
        // Category changes affect products display
        $this->clearProductCache();
    }

    /**
     * Clear banner cache
     */
    public function clearBannerCache(): void
    {
        Cache::forget(self::HOMEPAGE_BANNERS);
    }

    /**
     * Clear all cache (use with caution)
     */
    public function clearAllCache(): void
    {
        Cache::flush();
    }
}

