// ============================================
// LocalStorage Service Implementation
// Browser localStorage backend for StorageService
// ============================================

import { browser } from '$app/environment';
import type { StorageService } from './storage';

/**
 * LocalStorage implementation of StorageService.
 * Handles JSON serialization/deserialization automatically.
 * Safe for SSR - returns null/no-op when not in browser.
 */
class LocalStorageService implements StorageService {
    /**
     * Get a value from localStorage
     * @param key Storage key
     * @returns Parsed value or null if not found/invalid
     */
    get<T>(key: string): T | null {
        if (!browser) return null;

        try {
            const item = localStorage.getItem(key);
            if (item === null) return null;
            return JSON.parse(item) as T;
        } catch (error) {
            console.warn(`[Storage] Failed to parse key "${key}":`, error);
            return null;
        }
    }

    /**
     * Set a value in localStorage
     * @param key Storage key
     * @param value Value to store (will be JSON serialized)
     */
    set<T>(key: string, value: T): void {
        if (!browser) return;

        try {
            const serialized = JSON.stringify(value);
            localStorage.setItem(key, serialized);
        } catch (error) {
            console.error(`[Storage] Failed to set key "${key}":`, error);
        }
    }

    /**
     * Remove a value from localStorage
     * @param key Storage key
     */
    remove(key: string): void {
        if (!browser) return;
        localStorage.removeItem(key);
    }

    /**
     * Check if a key exists in localStorage
     * @param key Storage key
     */
    has(key: string): boolean {
        if (!browser) return false;
        return localStorage.getItem(key) !== null;
    }

    /**
     * Clear all localStorage data
     * Use with caution - affects all stored data
     */
    clear(): void {
        if (!browser) return;
        localStorage.clear();
    }

    /**
     * Get raw string value without JSON parsing
     * Useful for checking data format or migration
     */
    getRaw(key: string): string | null {
        if (!browser) return null;
        return localStorage.getItem(key);
    }

    /**
     * Set raw string value without JSON serialization
     * Useful for storing pre-serialized data
     */
    setRaw(key: string, value: string): void {
        if (!browser) return;
        localStorage.setItem(key, value);
    }

    /**
     * List all keys matching a prefix
     * @param prefix Key prefix to filter by
     * @returns Array of matching keys
     */
    keys(prefix?: string): string[] {
        if (!browser) return [];

        const allKeys: string[] = [];
        for (let i = 0; i < localStorage.length; i++) {
            const key = localStorage.key(i);
            if (key) {
                if (!prefix || key.startsWith(prefix)) {
                    allKeys.push(key);
                }
            }
        }
        return allKeys;
    }
}

// Export singleton instance
export const localStorageService = new LocalStorageService();
