package cy.hexor.furumi.data.local

import android.content.Context
import dagger.hilt.android.qualifiers.ApplicationContext
import java.util.UUID
import javax.inject.Inject
import javax.inject.Singleton

@Singleton
class ConnectedDeviceStorage @Inject constructor(
    @ApplicationContext context: Context
) {
    private val prefs = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE)

    fun getOrCreateDeviceId(): String {
        prefs.getString(KEY_DEVICE_ID, null)
            ?.takeIf { it.matches(DEVICE_ID_REGEX) }
            ?.let { return it }

        val deviceId = "android_${UUID.randomUUID().toString().replace("-", "")}"
        prefs.edit()
            .putString(KEY_DEVICE_ID, deviceId)
            .apply()
        return deviceId
    }

    private companion object {
        const val PREFS_NAME = "connected_device"
        const val KEY_DEVICE_ID = "device_id"
        val DEVICE_ID_REGEX = Regex("^[a-zA-Z0-9_-]{1,128}$")
    }
}
