// src/domain/normalize/chargingStatus.js

const toNum = (v) => {
    if (v === null || v === undefined || v === '') return 0;
    const n = typeof v === 'number' ? v : parseFloat(v);
    return Number.isFinite(n) ? n : 0;
};

const toArr3 = (v) => {
    if (Array.isArray(v)) return [toNum(v[0]), toNum(v[1]), toNum(v[2])];
    if (v && typeof v === 'object') return [toNum(v.l1), toNum(v.l2), toNum(v.l3)];
    return [0, 0, 0];
};

const normalizeStatusText = (rawStatus) => {
    const s = String(rawStatus || '').toLowerCase();

    if (s.includes('charging')) return '⚡ Charging';
    if (s.includes('ready')) return '🟢 Ready';
    if (s.includes('fault') || s.includes('error')) return '⚠️ Fault';
    if (s.includes('wait')) return '⚡ Wait';
    if (s.includes('not conn') || s.includes('disconnected')) return '🔌 Not Conn.';
    if (s.includes('vent')) return '💨 Vent';

    return rawStatus || '—';
};

/**
 * Normaliza eventos de status (realtime) vindos do mqtt -> socket
 */
function normalizeChargingStatus(data = {}) {
    const chargerId = data.charger_id || data.chargerId || data.id;

    const powerArr = toArr3(data.power || data.raw?.power);
    const voltageArr = toArr3(data.voltage || data.raw?.voltage);
    const currentArr = toArr3(data.current || data.raw?.current);

    const status = normalizeStatusText(data.status || data.state || data.raw?.state);

    const chargingTime =
        toNum(data.charging_time) ||
        toNum(data.chargingTime) ||
        toNum(data.raw?.chargingTime) ||
        toNum(data.raw?.sessionTime);

    const consumption = toNum(data.consumption) || toNum(data.raw?.consumption);

    const chargingCurrent =
        toNum(data.charging_current) ||
        toNum(data.chargingCurrent) ||
        currentArr[0];

    return {
        charger_id: chargerId,
        mqtt_topic: data.mqtt_topic || data.mqttTopic,

        status,
        stateCode: data.stateCode || data.raw?.stateCode || undefined,

        consumption,
        charging_time: chargingTime,
        charging_current: chargingCurrent,

        power: powerArr,
        voltage: voltageArr,
        current: currentArr,

        raw: data.raw || data,
        updated_at: new Date().toISOString(),
    };
}

module.exports = { normalizeChargingStatus };
