"use client";

import { useMemo } from "react";
import { useQuery } from "@tanstack/react-query";
import Cookies from "js-cookie";
import { fetchStoriesFeed } from "@/api/fetchStories";

export function useStoryMetaForUser(userId?: string | null) {
  const token = Cookies.get("token") || "";

  const { data } = useQuery({
    queryKey: ["stories-feed", token],
    queryFn: () => fetchStoriesFeed(token),
    enabled: Boolean(token && userId),
    staleTime: 60_000,
  });

  return useMemo(() => {
    if (!userId || !data) {
      return { hasStory: false, hasUnviewed: false };
    }

    const id = String(userId);

    if (data.my_story && String(data.my_story.user._id) === id) {
      return {
        hasStory: data.my_story.stories.length > 0,
        hasUnviewed: data.my_story.has_unviewed,
      };
    }

    const item = data.feed.find((entry) => String(entry.user._id) === id);
    return {
      hasStory: (item?.stories.length ?? 0) > 0,
      hasUnviewed: item?.has_unviewed ?? false,
    };
  }, [data, userId]);
}
