/**
 * Firebase RTDB / mixed client order timestamps and POS vs online channel helpers.
 */

/**
 * @param {unknown} raw
 * @returns {number|null} epoch ms
 */
export function firebaseTimestampToMs(raw) {
    if (raw == null) return null;
    if (typeof raw === 'number' && Number.isFinite(raw)) return raw;
    if (typeof raw === 'string') {
        const t = Date.parse(raw);
        return Number.isNaN(t) ? null : t;
    }
    if (raw instanceof Date) {
        const t = raw.getTime();
        return Number.isNaN(t) ? null : t;
    }
    if (typeof raw === 'object') {
        const sec = raw.seconds ?? raw._seconds;
        if (typeof sec === 'number' && Number.isFinite(sec)) {
            const ns = raw.nanoseconds ?? raw._nanoseconds ?? 0;
            return sec * 1000 + Math.floor(Number(ns) / 1e6);
        }
    }
    return null;
}

/**
 * @param {unknown} order
 * @returns {number|null}
 */
export function getOrderCreatedAtMs(order) {
    if (!order || typeof order !== 'object') return null;
    const raw = order.createdAt ?? order.timestamp ?? order.capturedAt;
    const direct = firebaseTimestampToMs(raw);
    if (direct != null) return direct;
    const d = new Date(raw);
    const t = d.getTime();
    return Number.isNaN(t) ? null : t;
}

/**
 * @param {unknown} order
 * @returns {'pos'|'online'|'unknown'}
 */
export function classifyOrderChannel(order) {
    if (!order || typeof order !== 'object') return 'unknown';
    const c = String(order.channel ?? order.salesChannel ?? '')
        .trim()
        .toLowerCase();
    if (c === 'pos') return 'pos';
    if (!c) return 'unknown';
    return 'online';
}
