import { useState, useRef } from "react";

export function useVideoWatch(videoId: number, initialWatched: boolean) {
    const [watched, setWatched] = useState(initialWatched);
    const alreadySent = useRef(false);

    const markAsWatched = async () => { 
        if (alreadySent.current || watched ) return;

        alreadySent.current = true;

        try {
            await fetch(`http://127.0.0.1:8000/api/video/${videoId}/watch`, {
                method: "POST",
                headers: {
                    Accept: "application/json",
                    Authorization: `Bearer ${localStorage.getItem("token")}`
                },
            });

            setWatched(true);
        } catch (error) {
            console.error("Erro ao marcar o vídeo como assistido: ", error);
            alreadySent.current = false;
        }
    }

    return { watched, markAsWatched };
}