package com.dmc.callcrm.sync import android.content.Context import android.util.Log import com.dmc.callcrm.data.CallLogReader import com.dmc.callcrm.data.Prefs import com.dmc.callcrm.network.ApiClient import com.dmc.callcrm.network.SyncRequest /** The one place that reads new calls and pushes them to the server. */ object Syncer { private const val TAG = "Syncer" suspend fun run(ctx: Context): Boolean { val prefs = Prefs(ctx) if (!prefs.isRegistered) return false val reader = CallLogReader(ctx) // phoneAccountId filtering can be wired to the chosen SIM; null = all calls on device. val batch = reader.readSince(prefs.lastCallDate, phoneAccountId = null) if (batch.calls.isEmpty()) return true return try { val resp = ApiClient.service.syncCalls(prefs.bearer(), SyncRequest(batch.calls)) if (resp.isSuccessful && resp.body()?.ok == true) { prefs.lastCallDate = batch.maxDate // advance the cursor Log.d(TAG, "synced ${batch.calls.size}, inserted ${resp.body()?.inserted}") true } else { Log.w(TAG, "sync failed: ${resp.code()} ${resp.errorBody()?.string()}") false } } catch (e: Exception) { Log.e(TAG, "sync error", e) false } } }