"use client";

import { useEffect } from "react";
import type { ChatMessage } from "@/components/chat/ChatMessageCard";
import type { QueryKey } from "@tanstack/react-query";
import { useQueryClient } from "@tanstack/react-query";

type ThreadCache = {
  pages: { messages: ChatMessage[] }[];
};

export function useTimedMessageExpiry(
  messages: ChatMessage[],
  queryKey: QueryKey,
  onExpirePending?: (ids: string[]) => void
) {
  const queryClient = useQueryClient();

  useEffect(() => {
    const purge = () => {
      const now = Date.now();
      const expired = messages.filter((m) => {
        if (!m.expiresAt) return false;
        const t = new Date(m.expiresAt).getTime();
        return !Number.isNaN(t) && t <= now;
      });
      if (!expired.length) return;

      const idSet = new Set(expired.map((m) => m._id));

      queryClient.setQueryData(queryKey, (oldData: ThreadCache | undefined) => {
        if (!oldData?.pages?.length) return oldData;
        return {
          ...oldData,
          pages: oldData.pages.map((page) => ({
            ...page,
            messages: page.messages.filter((m) => !idSet.has(m._id)),
          })),
        };
      });

      const pendingIds = expired
        .filter((m) => m._id.startsWith("temp-"))
        .map((m) => m._id);
      if (pendingIds.length) onExpirePending?.(pendingIds);
    };

    purge();
    const timer = setInterval(purge, 1000);
    return () => clearInterval(timer);
  }, [messages, queryKey, queryClient, onExpirePending]);
}
