import { useEffect, useRef } from "react";
import { viewService } from "@/services/viewService";

/**
 * Fires add_view once per unique contentType+contentId+episodeId combination per session.
 * Mirrors Flutter: episode_id only sent when provided (podcast episodes).
 * Safe to call with null/undefined — does nothing until contentType and contentId are truthy.
 */
export function useAddView(
  contentType: number | null | undefined,
  contentId: string | null | undefined,
  episodeId?: string,
) {
  const firedRef = useRef<string | null>(null);

  useEffect(() => {
    if (!contentType || !contentId) return;
    const key = `${contentType}-${contentId}-${episodeId ?? ""}`;
    if (firedRef.current === key) return;
    firedRef.current = key;
    viewService.addView(contentType, contentId, episodeId).catch(() => {});
  }, [contentType, contentId, episodeId]);
}
