import { Post } from "@/types/types";
import { prefetchPostVideo } from "@/lib/videoPreload";

const KEY_PREFIX = "reels-seed-post-";

export function cacheReelsSeedPost(post: Post): void {
  if (typeof window === "undefined") return;
  try {
    sessionStorage.setItem(`${KEY_PREFIX}${post._id}`, JSON.stringify(post));
    prefetchPostVideo(post, "high");
  } catch {
    /* ignore quota errors */
  }
}

export function readReelsSeedPost(id: string): Post | null {
  if (typeof window === "undefined") return null;
  try {
    const raw = sessionStorage.getItem(`${KEY_PREFIX}${id}`);
    if (!raw) return null;
    return JSON.parse(raw) as Post;
  } catch {
    return null;
  }
}

export function updateReelsSeedPostEngagement(
  postId: string,
  patch: Partial<Pick<Post, "is_liked" | "likesCount" | "is_saved" | "savesCount">>
): void {
  if (typeof window === "undefined") return;
  try {
    const key = `${KEY_PREFIX}${postId}`;
    const raw = sessionStorage.getItem(key);
    if (!raw) return;
    const post = JSON.parse(raw) as Post;
    sessionStorage.setItem(key, JSON.stringify({ ...post, ...patch }));
  } catch {
    /* ignore */
  }
}
