// src/mqtt/handlers/legacy.handler.js
async function handleLegacyState(ctx, mqttTopic, payload) {
    const charger = await ctx.getChargerByMqttTopic(mqttTopic);
    if (!charger) {
        console.warn(`[MQTT] Charger não encontrado para topic: ${mqttTopic}`);
        return;
    }

    const chargerId = charger.id;
    const now = new Date();

    const stateCode = ctx.inferStateCode(payload?.state);
    if (!stateCode) return;

    const status = ctx.getStatusFromStateCode(stateCode);
    ctx.lastMetaByChargerId.set(chargerId, { status, stateCode, rawStatus: payload?.state });

    // legacy arrays (assumimos W -> converter p/ kW)
    const powerArrKw = ctx.toArr3Kw2(payload?.power);
    const voltageArr = ctx.toArr3(payload?.voltage);
    const currentArr = ctx.toArr3(payload?.current);

    // ✅ 2 casas
    const consumption = ctx.round2(payload?.consumption);

    // ⚠️ se o teu charging_time no DB ainda for INTEGER, mete Math.round aqui.
    // Como disseste que ajustaste a DB para decimais, mantemos 2 casas:
    const chargingTime = ctx.round2(payload?.chargingTime ?? payload?.sessionTime);

    const dbUpdate = {
        status,
        charging_current: currentArr[0],
        consumption,
        charging_time: chargingTime,

        power_l1: powerArrKw[0],
        power_l2: powerArrKw[1],
        power_l3: powerArrKw[2],

        voltage_l1: voltageArr[0],
        voltage_l2: voltageArr[1],
        voltage_l3: voltageArr[2],

        current_l1: currentArr[0],
        current_l2: currentArr[1],
        current_l3: currentArr[2],

        updated_at: now.toISOString(),
    };

    await ctx.updateChargerDbIfChanged(chargerId, dbUpdate);

    ctx.emitter.emit('charging-status', {
        charger_id: chargerId,
        mqtt_topic: mqttTopic,
        status,
        stateCode,
        consumption,
        chargingTime,
        power: powerArrKw,
        voltage: voltageArr,
        current: currentArr,
        raw: payload,
    });
}

async function handleLegacyConfigResponse(ctx, mqttTopic, payload) {
    const charger = await ctx.getChargerByMqttTopic(mqttTopic);
    if (!charger) return;

    const configData = {
        charger_id: charger.id,
        max_charging_current: payload?.maxChargingCurrent || 32,
        require_auth: !!payload?.requireAuth,
        rcm_enabled: !!payload?.rcm,
        temperature_limit: payload?.temperatureThreshold || 60,
        config_received_at: new Date().toISOString(),
    };

    const existingConfig = await ctx.db('charger_configs').where({ charger_id: charger.id }).first();

    if (existingConfig) {
        await ctx.db('charger_configs').where({ charger_id: charger.id }).update(configData);
    } else {
        await ctx.db('charger_configs').insert(configData);
    }

    ctx.emitter.emit('charging-config', {
        ...configData,
        mqtt_topic: mqttTopic,
        raw: payload,
    });
}

module.exports = { handleLegacyState, handleLegacyConfigResponse };
