/**
 * Lightweight RTDB summary for cross-page KPIs (written from dashboard home recompute).
 * Path: `clients/{clientId}/dashboardSummary/latest`
 *
 * @param {import('https://www.gstatic.com/firebasejs/11.9.0/firebase-database.js').Database} db
 * @param {string} clientId
 * @param {Record<string, unknown>} chartData Output of `UI.processDashboardData(...)`
 */
import { ref, set } from 'https://www.gstatic.com/firebasejs/11.9.0/firebase-database.js';

const SCHEMA_VERSION = 1;

/** @param {Record<string, unknown>} chartData */
export function buildDashboardSummaryPayload(chartData) {
    if (!chartData || typeof chartData !== 'object') return null;
    return {
        schemaVersion: SCHEMA_VERSION,
        updatedAtMs: Date.now(),
        totalSales: Number(chartData.totalSales) || 0,
        totalIncome: Number(chartData.totalIncome) || 0,
        paidOrders: Number(chartData.paidOrders) || 0,
        totalVisitors: Number(chartData.totalVisitors) || 0,
        currentPeriodRangeLabel: chartData.currentPeriodRangeLabel
            ? String(chartData.currentPeriodRangeLabel)
            : '',
        comparisonRangeLabel: chartData.comparisonRangeLabel
            ? String(chartData.comparisonRangeLabel)
            : ''
    };
}

let publishTimer = null;

/**
 * Debounced write so rapid `onValue` bursts do not spam RTDB.
 * Failures are silent (permission / offline).
 * @param {import('https://www.gstatic.com/firebasejs/11.9.0/firebase-database.js').Database} db
 * @param {string} clientId
 * @param {Record<string, unknown>} chartData
 * @param {number} [debounceMs]
 */
export function schedulePublishDashboardSummary(db, clientId, chartData, debounceMs = 2800) {
    if (!db || !clientId) return;
    const payload = buildDashboardSummaryPayload(chartData);
    if (!payload) return;
    if (publishTimer) clearTimeout(publishTimer);
    publishTimer = setTimeout(() => {
        publishTimer = null;
        const r = ref(db, `clients/${clientId}/dashboardSummary/latest`);
        set(r, payload).catch(() => {});
    }, debounceMs);
}
