/**
 * Inventory movement ledger helpers (Firebase RTDB).
 * Path: clients/{clientId}/inventoryLedger/{eventId}
 */

/** @typedef {'sale'|'purchase'|'refund'|'adjustment'|'wastage'|'transfer_out'|'transfer_in'} LedgerEventType */

/**
 * @param {LedgerEventType} eventType
 * @param {object} o
 */
export function buildLedgerEvent(eventType, o) {
    const {
        productId,
        variantId = null,
        qtyDelta,
        uom = 'unit',
        weightKg = null,
        unitCost = null,
        unitSell = null,
        beforeQty = null,
        afterQty = null,
        sourceRef = null,
        note = '',
        createdByUid = null,
        costMethod = null,
        costSourceRef = null,
        schemaVersion: schemaOverride = null
    } = o;
    const out = {
        eventType,
        productId: String(productId),
        variantId: variantId != null && variantId !== '' ? String(variantId) : null,
        qtyDelta: Number(qtyDelta),
        uom: String(uom || 'unit'),
        weightKg: weightKg == null ? null : Number(weightKg),
        unitCost: unitCost == null ? null : Number(unitCost),
        unitSell: unitSell == null ? null : Number(unitSell),
        beforeQty: beforeQty === null || beforeQty === undefined ? null : Number(beforeQty),
        afterQty: afterQty === null || afterQty === undefined ? null : Number(afterQty),
        sourceRef: sourceRef && typeof sourceRef === 'object' ? sourceRef : null,
        note: String(note || '').slice(0, 500),
        createdByUid: createdByUid != null ? String(createdByUid) : null,
        costMethod: costMethod == null ? null : String(costMethod),
        costSourceRef: costSourceRef && typeof costSourceRef === 'object' ? costSourceRef : null
    };
    let sv = 1;
    if (schemaOverride != null && !Number.isNaN(Number(schemaOverride))) sv = Number(schemaOverride);
    else if ((eventType === 'sale' || eventType === 'refund') && out.unitCost != null) sv = 2;
    else if (out.costMethod) sv = 2;
    out.schemaVersion = sv;
    return out;
}

/**
 * Append ledger rows to a multi-path `update(ref(db), updates)` map (full paths from DB root).
 * @param {Record<string, unknown>} updates
 * @param {{ db: any, clientId: string, ref: any, push: any, serverTimestamp: () => unknown }} fb
 * @param {Array<ReturnType<typeof buildLedgerEvent>>} events
 */
export function appendLedgerToRootUpdates(updates, fb, events) {
    const { db, clientId, ref, push, serverTimestamp } = fb;
    const root = `clients/${clientId}/inventoryLedger`;
    for (const ev of events) {
        const k = push(ref(db, root)).key;
        if (!k) continue;
        updates[`${root}/${k}`] = {
            ...ev,
            createdAt: serverTimestamp()
        };
    }
    return updates;
}

/**
 * Append ledger rows to updates relative to `clients/{clientId}` root ref.
 * @param {Record<string, unknown>} relUpdates
 * @param {{ db: any, clientId: string, ref: any, push: any, serverTimestamp: () => unknown }} fb
 * @param {Array<ReturnType<typeof buildLedgerEvent>>} events
 */
export function appendLedgerToClientRelativeUpdates(relUpdates, fb, events) {
    const { db, clientId, ref, push, serverTimestamp } = fb;
    const out = { ...relUpdates };
    const base = 'inventoryLedger';
    for (const ev of events) {
        const k = push(ref(db, `clients/${clientId}/${base}`)).key;
        if (!k) continue;
        out[`${base}/${k}`] = {
            ...ev,
            createdAt: serverTimestamp()
        };
    }
    return out;
}
