/**
 * Compact dashboard analytics blob for read-optimized clients (optional).
 * Path: `clients/{clientId}/dashboardAnalytics/latest`
 */
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 buildDashboardAnalyticsPayload(chartData) {
    if (!chartData || typeof chartData !== 'object') return null;
    const cat = chartData.categorySales && typeof chartData.categorySales === 'object' ? chartData.categorySales : {};
    const topCategories = Object.entries(cat)
        .map(([name, amount]) => ({ name: String(name), amount: Number(amount) || 0 }))
        .sort((a, b) => b.amount - a.amount)
        .slice(0, 12);
    const ps = chartData.productSalesCount && typeof chartData.productSalesCount === 'object' ? chartData.productSalesCount : {};
    const topProducts = Object.entries(ps)
        .map(([id, row]) => ({
            id: String(id),
            name: row && typeof row === 'object' ? String(row.name || id) : String(id),
            count: row && typeof row === 'object' ? Number(row.count) || 0 : 0,
            totalEarned: row && typeof row === 'object' ? Number(row.totalEarned) || 0 : 0
        }))
        .sort((a, b) => b.totalEarned - a.totalEarned)
        .slice(0, 10);
    return {
        schemaVersion: SCHEMA_VERSION,
        updatedAtMs: Date.now(),
        labels7Days: Array.isArray(chartData.labels7Days) ? chartData.labels7Days : [],
        dailySales: Array.isArray(chartData.dailySales) ? chartData.dailySales.slice(0, 7) : [],
        dailyIncome: Array.isArray(chartData.dailyIncome) ? chartData.dailyIncome.slice(0, 7) : [],
        dailyOrders: Array.isArray(chartData.dailyOrders) ? chartData.dailyOrders.slice(0, 7) : [],
        dailyVisitors: Array.isArray(chartData.dailyVisitors) ? chartData.dailyVisitors.slice(0, 7) : [],
        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) : '',
        kpiTrendSalesPct: Number(chartData.kpiTrendSalesPct) || 0,
        kpiTrendIncomePct: Number(chartData.kpiTrendIncomePct) || 0,
        kpiTrendOrdersPct: Number(chartData.kpiTrendOrdersPct) || 0,
        kpiTrendVisitorsPct: Number(chartData.kpiTrendVisitorsPct) || 0,
        topCategories,
        topProducts
    };
}

let analyticsPublishTimer = null;

/**
 * @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 schedulePublishDashboardAnalytics(db, clientId, chartData, debounceMs = 3200) {
    if (!db || !clientId) return;
    const payload = buildDashboardAnalyticsPayload(chartData);
    if (!payload) return;
    if (analyticsPublishTimer) clearTimeout(analyticsPublishTimer);
    analyticsPublishTimer = setTimeout(() => {
        analyticsPublishTimer = null;
        const r = ref(db, `clients/${clientId}/dashboardAnalytics/latest`);
        set(r, payload).catch(() => {});
    }, debounceMs);
}
