/**
 * Hook to check chat status for multiple fields at once
 * Returns a mapping of field_id -> ChatStatus ('none' | 'has_messages' | 'has_unread')
 * Used by HazoCollabFormView in edit and summary modes
 */
'use client';
import { useState, useEffect, useCallback, 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 chat status for multiple fields at once
 * Efficiently batches checks and returns status mapping
 */
export function use_field_chat_status({ field_ids, chat_group_id, enabled = true, realtime_mode = 'polling', poll_interval = DEFAULTS.poll_interval_ms, }) {
    const logger = use_logger();
    const [chat_status, set_chat_status] = useState({});
    const [is_loading, set_is_loading] = useState(false);
    const [current_user_id, set_current_user_id] = useState(undefined);
    // Use ref to track if initial fetch has been done (for manual mode)
    const initial_fetch_done_ref = useRef(false);
    // Create stable key for field_ids to prevent unnecessary callback recreation
    const field_ids_key = field_ids.join(',');
    // Store field_ids in ref to use in callback without triggering recreation
    const field_ids_ref = useRef(field_ids);
    field_ids_ref.current = field_ids;
    // Fetch current user ID on mount
    useEffect(() => {
        const fetch_current_user = async () => {
            try {
                const auth_response = await fetch(API_ENDPOINTS.auth_me);
                if (auth_response.ok) {
                    const auth_data = await auth_response.json();
                    if (auth_data.authenticated && auth_data.user_id) {
                        set_current_user_id(auth_data.user_id);
                    }
                }
            }
            catch (error) {
                logger.error('[use_field_chat_status] Could not fetch current user', {
                    error: error instanceof Error ? error.message : String(error),
                });
            }
        };
        fetch_current_user();
    }, [logger]);
    // Check chat messages for all fields - stable callback using refs
    const check_chat_messages = useCallback(async () => {
        const current_field_ids = field_ids_ref.current;
        if (!current_user_id || !chat_group_id || !enabled || current_field_ids.length === 0) {
            logger.debug('[use_field_chat_status] Skipping check - missing requirements', {
                has_current_user_id: !!current_user_id,
                has_chat_group_id: !!chat_group_id,
                enabled,
                field_count: current_field_ids.length,
            });
            return;
        }
        try {
            set_is_loading(true);
            // Track status per field
            const field_status_map = new Map();
            logger.debug('[use_field_chat_status] Checking chat messages for fields', {
                field_ids: current_field_ids,
                user_id: current_user_id,
                chat_group_id,
            });
            // Probe first field to detect systematic errors (invalid chat_group_id, auth issues)
            // before firing N parallel requests that would all fail identically
            const first_field_id = current_field_ids[0];
            const probe_params = new URLSearchParams({
                chat_group_id: chat_group_id || '',
                reference_id: first_field_id,
            });
            const probe_response = await fetch(`${API_ENDPOINTS.chat_messages}?${probe_params.toString()}`);
            if (!probe_response.ok) {
                const is_systematic_error = probe_response.status === 400 || probe_response.status === 401 || probe_response.status === 403;
                if (is_systematic_error) {
                    // All subsequent requests would fail the same way - skip them
                    logger.warn('[use_field_chat_status] Chat API returned systematic error, skipping remaining fields', {
                        status: probe_response.status,
                        chat_group_id,
                        field_count: current_field_ids.length,
                    });
                    // Set all fields to 'none'
                    for (const field_id of current_field_ids) {
                        field_status_map.set(field_id, 'none');
                    }
                }
                else {
                    // Non-systematic error on first field, still try the rest
                    logger.error('[use_field_chat_status] Field API error', {
                        field_id: first_field_id,
                        status: probe_response.status,
                    });
                    field_status_map.set(first_field_id, 'none');
                    // Query remaining fields in parallel
                    const remaining_field_ids = current_field_ids.slice(1);
                    const check_promises = remaining_field_ids.map(async (field_id) => {
                        try {
                            const params = new URLSearchParams({
                                chat_group_id: chat_group_id || '',
                                reference_id: field_id,
                            });
                            const response = await fetch(`${API_ENDPOINTS.chat_messages}?${params.toString()}`);
                            if (response.ok) {
                                const data = await response.json();
                                const messages = data.messages || [];
                                const api_current_user_id = data.current_user_id;
                                const has_any_messages = Array.isArray(messages) && messages.length > 0;
                                const effective_current_user_id = api_current_user_id || current_user_id;
                                const has_unread = has_any_messages && messages.some((msg) => {
                                    const is_unread = msg.read_at === null || msg.read_at === undefined;
                                    const is_from_others = msg.sender_user_id !== effective_current_user_id;
                                    return is_unread && is_from_others;
                                });
                                field_status_map.set(field_id, has_unread ? 'has_unread' : has_any_messages ? 'has_messages' : 'none');
                            }
                            else {
                                field_status_map.set(field_id, 'none');
                            }
                        }
                        catch {
                            field_status_map.set(field_id, 'none');
                        }
                    });
                    await Promise.all(check_promises);
                }
            }
            else {
                // First field succeeded - process its result and query remaining fields
                const first_data = await probe_response.json();
                const first_messages = first_data.messages || [];
                const first_api_user_id = first_data.current_user_id;
                const first_has_messages = Array.isArray(first_messages) && first_messages.length > 0;
                const first_effective_user_id = first_api_user_id || current_user_id;
                const first_has_unread = first_has_messages && first_messages.some((msg) => {
                    const is_unread = msg.read_at === null || msg.read_at === undefined;
                    const is_from_others = msg.sender_user_id !== first_effective_user_id;
                    return is_unread && is_from_others;
                });
                field_status_map.set(first_field_id, first_has_unread ? 'has_unread' : first_has_messages ? 'has_messages' : 'none');
                // Query remaining fields in parallel
                const remaining_field_ids = current_field_ids.slice(1);
                if (remaining_field_ids.length > 0) {
                    const check_promises = remaining_field_ids.map(async (field_id) => {
                        try {
                            const params = new URLSearchParams({
                                chat_group_id: chat_group_id || '',
                                reference_id: field_id,
                            });
                            const response = await fetch(`${API_ENDPOINTS.chat_messages}?${params.toString()}`);
                            if (response.ok) {
                                const data = await response.json();
                                const messages = data.messages || [];
                                const api_current_user_id = data.current_user_id;
                                const has_any_messages = Array.isArray(messages) && messages.length > 0;
                                const effective_current_user_id = api_current_user_id || current_user_id;
                                const has_unread = has_any_messages && messages.some((msg) => {
                                    const is_unread = msg.read_at === null || msg.read_at === undefined;
                                    const is_from_others = msg.sender_user_id !== effective_current_user_id;
                                    return is_unread && is_from_others;
                                });
                                field_status_map.set(field_id, has_unread ? 'has_unread' : has_any_messages ? 'has_messages' : 'none');
                            }
                            else {
                                field_status_map.set(field_id, 'none');
                            }
                        }
                        catch {
                            field_status_map.set(field_id, 'none');
                        }
                    });
                    await Promise.all(check_promises);
                }
            }
            // Convert map to record
            const chat_status_record = {};
            field_status_map.forEach((status, field_id) => {
                chat_status_record[field_id] = status;
            });
            logger.debug('[use_field_chat_status] Chat status check complete', {
                chat_status_record,
            });
            set_chat_status(chat_status_record);
        }
        catch (error) {
            logger.error('[use_field_chat_status] Error checking chat status', {
                error: error instanceof Error ? error.message : String(error),
            });
            set_chat_status({});
        }
        finally {
            set_is_loading(false);
        }
    }, [current_user_id, chat_group_id, enabled, logger]);
    // Effect for initial fetch - runs once when requirements are met
    useEffect(() => {
        if (!current_user_id || !chat_group_id || !enabled) {
            return;
        }
        // In manual mode, only fetch once
        if (realtime_mode === 'manual') {
            if (!initial_fetch_done_ref.current) {
                initial_fetch_done_ref.current = true;
                check_chat_messages();
            }
            return;
        }
        // In polling mode, fetch immediately and set up interval
        check_chat_messages();
        const interval_id = setInterval(check_chat_messages, poll_interval);
        return () => clearInterval(interval_id);
    }, [current_user_id, chat_group_id, enabled, realtime_mode, poll_interval, check_chat_messages]);
    // Reset initial fetch flag when key dependencies change (allows re-fetch)
    useEffect(() => {
        initial_fetch_done_ref.current = false;
    }, [chat_group_id, field_ids_key]);
    return {
        chat_status,
        is_loading,
        current_user_id,
        refresh: check_chat_messages,
    };
}
//# sourceMappingURL=use_field_chat_status.js.map