"use client";
import { useEffect } from 'react';
import { isLocalStorageEnabled } from '@/lib/storagePolicy';

/**
 * Enforces localStorage policy: only auth-related keys are allowed.
 * Removes product/cache/cart related keys on mount.
 */
const ALLOWED_PREFIXES = ['auth_token', 'auth_user'];
const BLOCKED_PREFIXES = ['cache_', 'cart_', 'redis_cache', 'product_', 'categories', 'featured_', 'home_page_data'];

export function LocalStoragePolicyEnforcer() {
  useEffect(() => {
    if (typeof window === 'undefined') return;
    // Only enforce purge if policy disabled
    if (isLocalStorageEnabled()) return;
    try {
      const keys = Object.keys(localStorage);
      for (const key of keys) {
        const allowed = ALLOWED_PREFIXES.some(prefix => key.startsWith(prefix));
        const blocked = BLOCKED_PREFIXES.some(prefix => key.startsWith(prefix));
        if (!allowed && blocked) {
          localStorage.removeItem(key);
        }
        if (key.startsWith('cache_') && !allowed) {
          localStorage.removeItem(key);
        }
      }
    } catch (e) {
      console.warn('LocalStoragePolicy purge failed', e);
    }
  }, []);
  return null;
}

export default LocalStoragePolicyEnforcer;
