"use client";

import { useEffect, useRef } from "react";
import { historyService } from "@/services/historyService";
import { isLoggedIn } from "@/utils/auth";

/**
 * Adds the current content to the user's watch history after `delayMs` ms of play.
 * Fires once per content ID regardless of re-renders.
 * Pass `getStopTime` to capture the actual playback position at the moment the
 * timer fires (avoids stale-closure issues with a plain number prop).
 */
export function useAddToHistory(
  contentType: number | null | undefined,
  contentId: string | null | undefined,
  episodeId?: string,
  delayMs = 5000,
  getStopTime?: () => number,
) {
  const calledRef = useRef<string | null>(null);
  const getStopTimeRef = useRef(getStopTime);
  useEffect(() => { getStopTimeRef.current = getStopTime; });

  useEffect(() => {
    if (!contentType || !contentId) return;
    if (!isLoggedIn()) return;
    // Only fire once per unique contentId
    if (calledRef.current === contentId) return;

    const timer = setTimeout(() => {
      calledRef.current = contentId;
      const stopTime = Math.floor(getStopTimeRef.current?.() ?? 0);
      historyService
        .addToHistory({ contentType, contentId, episodeId, stopTime })
        .catch(() => {});
    }, delayMs);

    return () => clearTimeout(timer);
  }, [contentType, contentId, episodeId, delayMs]);
}
