/**
 * Hook to check if unread chat messages exist for a given reference_id
 * Used to determine if a field has active unread chat conversations
 * Updated for hazo_chat v3.0.0 - Group-based chat architecture
 */
'use client';
import { useState, useEffect, useRef } from 'react';
import { use_logger } from '../logger/context.js';
import { DEFAULTS } from '../config/defaults.js';
import { API_ENDPOINTS } from '../config/api_endpoints.js';
/**
 * Hook to check if unread chat messages exist for a given reference_id
 * Checks for messages in the specified chat group where read_at is null
 * @param options Configuration options
 * @returns Object with has_messages boolean and loading state
 */
export function use_chat_messages_check({ reference_id, reference_type = '', chat_group_id, enabled = true, realtime_mode = 'polling', poll_interval = DEFAULTS.poll_interval_ms, }) {
    const logger = use_logger();
    const [has_messages, set_has_messages] = useState(false);
    const [is_loading, set_is_loading] = useState(false);
    // Track if initial fetch has been done (for manual mode)
    const initial_fetch_done_ref = useRef(false);
    useEffect(() => {
        if (!enabled || !reference_id || !chat_group_id) {
            set_has_messages(false);
            return;
        }
        /**
         * Check for unread messages by calling the chat API
         * The API returns messages for the specified chat group
         * We filter for messages where read_at is null (unread)
         */
        const check_messages = async () => {
            try {
                set_is_loading(true);
                const params = new URLSearchParams({
                    chat_group_id,
                    reference_id,
                    ...(reference_type && { reference_type }),
                });
                const response = await fetch(`${API_ENDPOINTS.chat_messages}?${params.toString()}`);
                if (response.ok) {
                    const data = await response.json();
                    // Check if messages array exists and has items
                    // API returns { success: true, messages: [], current_user_id }
                    const messages = data.messages || data;
                    // Filter for unread messages only (read_at is null)
                    const unread_messages = Array.isArray(messages)
                        ? messages.filter((msg) => {
                            // Check if message is unread (read_at is null or undefined)
                            const is_unread = msg.read_at === null || msg.read_at === undefined;
                            return is_unread;
                        })
                        : [];
                    const has_messages_result = unread_messages.length > 0;
                    set_has_messages(has_messages_result);
                }
                else {
                    set_has_messages(false);
                }
            }
            catch (error) {
                logger.error('[use_chat_messages_check] Error checking messages', {
                    error: error instanceof Error ? error.message : String(error),
                    reference_id,
                    chat_group_id,
                });
                set_has_messages(false);
            }
            finally {
                set_is_loading(false);
            }
        };
        // In manual mode, only fetch once
        if (realtime_mode === 'manual') {
            if (!initial_fetch_done_ref.current) {
                initial_fetch_done_ref.current = true;
                check_messages();
            }
            return;
        }
        // In polling mode, fetch immediately and set up interval if poll_interval > 0
        check_messages();
        let interval_id = null;
        if (poll_interval > 0) {
            interval_id = setInterval(check_messages, poll_interval);
        }
        return () => {
            if (interval_id) {
                clearInterval(interval_id);
            }
        };
    }, [reference_id, reference_type, chat_group_id, enabled, realtime_mode, poll_interval, logger]);
    // Reset initial fetch flag when key dependencies change
    useEffect(() => {
        initial_fetch_done_ref.current = false;
    }, [reference_id, chat_group_id]);
    return { has_messages, is_loading };
}
//# sourceMappingURL=use_chat_messages_check.js.map