package com.omixlab.lckcontrol.service

import java.util.UUID
import java.util.concurrent.ConcurrentHashMap

data class ConnectedClient(
    val clientId: String,
    val clientName: String,
    val packageName: String,
    val callingUid: Int = 0,
    val activePlanId: String? = null,
    val connectedAt: Long = System.currentTimeMillis(),
)

class ClientTracker {

    private val clients = ConcurrentHashMap<String, ConnectedClient>()

    fun register(clientName: String, packageName: String, callingUid: Int): String {
        // Remove existing client with same packageName to prevent duplicates on reconnect
        clients.entries.removeIf { it.value.packageName == packageName }

        val clientId = UUID.randomUUID().toString()
        clients[clientId] = ConnectedClient(
            clientId = clientId,
            clientName = clientName,
            packageName = packageName,
            callingUid = callingUid,
        )
        return clientId
    }

    fun unregister(clientId: String): ConnectedClient? = clients.remove(clientId)

    fun unregisterByUid(uid: Int): List<ConnectedClient> {
        val removed = mutableListOf<ConnectedClient>()
        clients.entries.removeIf { entry ->
            if (entry.value.callingUid == uid) {
                removed.add(entry.value)
                true
            } else false
        }
        return removed
    }

    fun setActivePlan(clientId: String, planId: String?) {
        clients.computeIfPresent(clientId) { _, client ->
            client.copy(activePlanId = planId)
        }
    }

    fun getClient(clientId: String): ConnectedClient? = clients[clientId]

    fun getAll(): List<ConnectedClient> = clients.values.toList()

    fun count(): Int = clients.size
}
