/**
 * Inventory KPI snapshot for lightweight reads elsewhere.
 * Path: `clients/{clientId}/inventorySummary/latest`
 */
import { ref, set } from 'https://www.gstatic.com/firebasejs/11.9.0/firebase-database.js';

const SCHEMA_VERSION = 1;

/**
 * @param {import('https://www.gstatic.com/firebasejs/11.9.0/firebase-database.js').Database} db
 * @param {string} clientId
 * @param {{ productCount: number, categoryCount: number, lowStockCount: number }} stats
 */
export function schedulePublishInventorySummary(db, clientId, stats, debounceMs = 4000) {
    if (!db || !clientId || !stats) return;
    if (typeof window === 'undefined') return;
    window.__invSummaryPubTimer = window.__invSummaryPubTimer || null;
    if (window.__invSummaryPubTimer) clearTimeout(window.__invSummaryPubTimer);
    window.__invSummaryPubTimer = setTimeout(() => {
        window.__invSummaryPubTimer = null;
        const payload = {
            schemaVersion: SCHEMA_VERSION,
            updatedAtMs: Date.now(),
            productCount: Number(stats.productCount) || 0,
            categoryCount: Number(stats.categoryCount) || 0,
            lowStockProductCount: Number(stats.lowStockCount) || 0
        };
        set(ref(db, `clients/${clientId}/inventorySummary/latest`), payload).catch(() => {});
    }, debounceMs);
}
