const Redis = require('../DataBase/Redis.js')
const jkesRedisKeys = require('./redisKeys.js')

async function getLepaoSchedule(recordId) {
    const schedule = await Redis.get(jkesRedisKeys.lepaoSchedule(recordId))
    return schedule ? JSON.parse(schedule) : null
}

/**
 * 将 lepao_record.result（JKES end 接口 info）解析为列表/详情用的摘要字段
 */
async function enrichLepaoRecordRow(row) {
    let out = { ...row }
    if (row.id != null && Number(row.state) === 0) {
        const schedule = await getLepaoSchedule(row.id)
        out.lepao_schedule = schedule
        out.schedule = schedule
    }
    let jkes = null
    try {
        const r =
            typeof row.result === 'object' && row.result !== null
                ? row.result
                : JSON.parse(row.result || '{}')
        const rawDistance = r.distance != null ? Number(r.distance) : NaN
        const distanceKm =
            Number.isFinite(rawDistance) && rawDistance > 0
                ? Math.round((rawDistance / 1000) * 1000) / 1000
                : null
        jkes = {
            distance_km: distanceKm,
            use_time_sec: r.useTime != null ? Number(r.useTime) : null,
            run_status: r.status?.value ?? r.status,
            campus_status: r.dataStatus?.value ?? r.dataStatus,
            begin_time: r.beginTime,
            end_time: r.endTime
        }
    } catch {
        jkes = null
    }
    out.jkes_record = jkes
    return out
}

function stripInternalRecordId(row) {
    if (!row || typeof row !== 'object') return row
    const { id, ...rest } = row
    return rest
}

async function enrichLepaoRecordRowForApi(row) {
    const enriched = await enrichLepaoRecordRow(row)
    return stripInternalRecordId(enriched)
}

module.exports = { enrichLepaoRecordRow, enrichLepaoRecordRowForApi, stripInternalRecordId }
