import { browser } from '$app/environment';
import { getCurrentUserId } from '$lib/auth/auth.svelte';
import type { ChildHomework } from '$lib/features/homework/api/parentHomework';

const CACHE_PREFIX = 'classeo:parent-homework:cache:';
const MAX_AGE_MS = 24 * 60 * 60 * 1000; // 24h

interface CacheEntry {
	data: ChildHomework[];
	timestamp: number;
}

function cacheKey(): string | null {
	const userId = getCurrentUserId();
	return userId ? `${CACHE_PREFIX}${userId}` : null;
}

/**
 * Sauvegarde les devoirs en cache localStorage, scopé par utilisateur.
 */
export function cacheParentHomework(data: ChildHomework[]): void {
	if (!browser) return;

	const key = cacheKey();
	if (!key) return;

	const entry: CacheEntry = {
		data,
		timestamp: Date.now(),
	};

	try {
		localStorage.setItem(key, JSON.stringify(entry));
	} catch {
		// localStorage full — ignore silently
	}
}

/**
 * Récupère les devoirs depuis le cache si encore valides.
 */
export function getCachedParentHomework(): ChildHomework[] | null {
	if (!browser) return null;

	const key = cacheKey();
	if (!key) return null;

	try {
		const raw = localStorage.getItem(key);
		if (!raw) return null;

		const entry: CacheEntry = JSON.parse(raw);

		if (Date.now() - entry.timestamp > MAX_AGE_MS) {
			localStorage.removeItem(key);
			return null;
		}

		return entry.data;
	} catch {
		return null;
	}
}
