package com.enterprise.mdm.data.repo import android.content.Context import com.enterprise.mdm.data.api.LocationRequest import com.enterprise.mdm.data.api.LoginRequest import com.enterprise.mdm.data.api.RetrofitClient import com.enterprise.mdm.data.local.AppDatabase import com.enterprise.mdm.data.prefs.SessionManager import com.enterprise.mdm.device.DeviceInfoCollector import com.enterprise.mdm.device.PolicyManager class MdmRepository(context: Context) { private val appContext = context.applicationContext val session = SessionManager(appContext) private val api get() = RetrofitClient.api(session) private val collector = DeviceInfoCollector(appContext) private val policy = PolicyManager(appContext) private val db = AppDatabase.get(appContext) suspend fun login(email: String, password: String): Result = runCatching { val res = api.login(LoginRequest(email, password)) val body = res.body() if (res.isSuccessful && body?.success == true && body.token != null) { session.token = body.token } else error(body?.error ?: "Login failed") } suspend fun enroll(): Result = runCatching { val req = collector.buildRegister(policy.isDeviceOwner()) val res = api.registerDevice(req) val body = res.body() if (res.isSuccessful && body?.success == true && body.token != null) { session.token = body.token session.deviceId = body.device_id ?: 0 session.deviceUid = req.device_uid } else error(body?.error ?: "Enrollment failed") } suspend fun heartbeat(): Int = runCatching { api.heartbeat().body()?.pending_commands ?: 0 }.getOrDefault(0) suspend fun syncStatus(): Boolean = runCatching { api.sync(collector.buildSync()).body()?.success == true }.getOrDefault(false) suspend fun sendLocation(lat: Double, lng: Double, acc: Float?): Boolean = runCatching { api.updateLocation(LocationRequest(lat, lng, acc)).body()?.success == true }.getOrDefault(false) suspend fun processCommands(): Int = runCatching { val cmds = api.fetchCommands().body()?.commands ?: emptyList() for (c in cmds) { val (ok, msg) = executeCommand(c.command_type, c.payload) runCatching { api.respondCommand( com.enterprise.mdm.data.api.CommandResponseRequest(c.id, ok, msg) ) } } cmds.size }.getOrDefault(0) private fun executeCommand(type: String, payload: String?): Pair { val value = runCatching { payload?.let { org.json.JSONObject(it).optString("value") } }.getOrNull() ?: "" return when (type) { "lock" -> policy.lock() to "lock" "refresh" -> true to "refresh queued" "wallpaper" -> policy.setWallpaper(value) to "wallpaper" "password_policy" -> policy.setPasswordPolicy(value.toIntOrNull() ?: 6) to "password policy" "factory_reset" -> policy.factoryReset() to "factory reset" "notify" -> true to "notification handled" "install_app", "update_app", "remove_app", "wifi_config", "unlock" -> true to "acknowledged: $type" else -> false to "unknown command: $type" } } suspend fun offlineCount(): Int = db.offlineDao().count() fun logout() { session.clear(); RetrofitClient.reset() } }