import echo from '@/echo';
import { useEffect } from 'react';
import { ChatMessage, Discussion } from '../types';

interface UseRealtimeMessagesOptions {
    discussion: Discussion | null;
    isChannelManager: boolean;
    coHostId: number;
    setMessages: React.Dispatch<React.SetStateAction<ChatMessage[]>>;
}

export function useRealtimeMessages({ discussion, isChannelManager, coHostId, setMessages }: UseRealtimeMessagesOptions): void {
    useEffect(() => {
        if (!discussion || !isChannelManager) return;

        const channel = echo.private('messagerie.' + coHostId);

        const handler = (e: any) => {
            if (String(e.discussionId) !== String(discussion.id)) return;

            fetch(`/guest-communication/discussions/${discussion.id}/messages`)
                .then((r) => r.json())
                .then((fresh: ChatMessage[]) => {
                    setMessages((prev) => {
                        // Real message IDs only (exclude optimistic local_* ones)
                        const realIds = new Set(
                            prev.filter((m) => !String(m.message_id).startsWith('local_')).map((m) => m.message_id),
                        );
                        const newOnes = fresh.filter((m) => !realIds.has(m.message_id));
                        if (newOnes.length === 0) return prev;
                        // Drop optimistic messages — real versions are now in newOnes
                        const withoutOptimistic = prev.filter((m) => !String(m.message_id).startsWith('local_'));
                        return [...withoutOptimistic, ...newOnes];
                    });
                })
                .catch(() => {});
        };

        channel.listen('.new-chat-message', handler);

        return () => {
            channel.stopListening('.new-chat-message', handler);
        };
    }, [discussion?.id, isChannelManager, coHostId]);
}
