package com.dmc.callcrm.data import android.provider.CallLog import android.util.Log import com.dmc.callcrm.network.ApiClient private const val TAG = "WhatsappCalls" /** * Fetches this employee's WhatsApp calls from the server and maps them into the same * CallStats.CallItem shape used for phone calls, so they can be merged into the * Analysis-tab detail functions (topCallerDetail, longestCallDetail, etc. — see their * optional `whatsappItems` param). Returns an empty list on any failure or if the app * isn't registered yet; callers should treat this the same as "no WhatsApp calls found" * rather than surfacing a separate error, matching how AnalyticsFragment's Summary tab * already handles this fetch. */ suspend fun fetchWhatsappCallItems(prefs: Prefs): List { if (!prefs.isRegistered) return emptyList() return try { val resp = ApiClient.service.whatsappCallsList(prefs.bearer()) if (!resp.isSuccessful) { Log.w(TAG, "whatsappCallsList failed: HTTP ${resp.code()}") } val df = java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss", java.util.Locale.getDefault()) resp.body()?.calls.orEmpty().mapNotNull { w -> val startedMs = try { df.parse(w.startedAt)?.time } catch (_: Exception) { null } ?: return@mapNotNull null val type = when (w.callType) { "incoming" -> CallLog.Calls.INCOMING_TYPE else -> CallLog.Calls.OUTGOING_TYPE } CallStats.CallItem( id = "wa_${w.id}", number = w.contactName, name = w.contactName, type = type, dateMs = startedMs, durationSec = w.durationSec, simSlot = null, source = "whatsapp" ) } } catch (e: Exception) { Log.w(TAG, "whatsappCallsList fetch failed: ${e.message}", e) emptyList() } }