import { useCallback } from "react";
import { PublishPrefetchCache } from "@/shared/types/publish";

const PREFETCH_KEY = "vigent_publish_prefetch_v1";
const PREFETCH_TTL = 2 * 60 * 1000; // 2 分钟

/**
 * 发布预加载缓存 hook
 * 用于在首页预加载发布页所需的账号和视频数据
 */
export const usePublishPrefetch = () => {
    const readPrefetch = useCallback((): PublishPrefetchCache | null => {
        if (typeof window === "undefined") return null;
        const raw = sessionStorage.getItem(PREFETCH_KEY);
        if (!raw) return null;
        try {
            const cache = JSON.parse(raw) as PublishPrefetchCache;
            if (!cache?.ts) return null;
            if (Date.now() - cache.ts > PREFETCH_TTL) return null;
            return cache;
        } catch {
            return null;
        }
    }, []);

    const updatePrefetch = useCallback((patch: Partial<PublishPrefetchCache>) => {
        if (typeof window === "undefined") return;
        const existing = (() => {
            const raw = sessionStorage.getItem(PREFETCH_KEY);
            if (!raw) return { ts: Date.now() };
            try {
                const cache = JSON.parse(raw) as PublishPrefetchCache;
                if (!cache?.ts || Date.now() - cache.ts > PREFETCH_TTL) return { ts: Date.now() };
                return cache;
            } catch {
                return { ts: Date.now() };
            }
        })();
        const next = { ...existing, ...patch, ts: Date.now() };
        sessionStorage.setItem(PREFETCH_KEY, JSON.stringify(next));
    }, []);

    const clearPrefetch = useCallback(() => {
        if (typeof window === "undefined") return;
        sessionStorage.removeItem(PREFETCH_KEY);
    }, []);

    return {
        readPrefetch,
        updatePrefetch,
        clearPrefetch,
    };
};
