package pl.firmatpp.kierowca.data

import android.content.Context
import android.os.Build
import android.provider.Settings
import pl.firmatpp.kierowca.BuildConfig
import pl.firmatpp.kierowca.data.model.DriverDeviceInfo

class DeviceInfoProvider(
    private val context: Context,
    private val tokenStore: TokenStore,
) {
    suspend fun currentDeviceInfo(): DriverDeviceInfo =
        DriverDeviceInfo(
            deviceId = tokenStore.deviceId(),
            androidId = Settings.Secure.getString(context.contentResolver, Settings.Secure.ANDROID_ID),
            brand = Build.BRAND,
            manufacturer = Build.MANUFACTURER,
            model = Build.MODEL,
            device = Build.DEVICE,
            product = Build.PRODUCT,
            androidVersion = Build.VERSION.RELEASE,
            sdkInt = Build.VERSION.SDK_INT,
            appVersion = BuildConfig.VERSION_NAME,
            serialNumber = readSerialNumber(),
        )

    private fun readSerialNumber(): String? =
        runCatching {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                Build.getSerial()
            } else {
                @Suppress("DEPRECATION")
                Build.SERIAL
            }
        }.getOrNull()
            ?.takeUnless { it.isBlank() || it.equals(Build.UNKNOWN, ignoreCase = true) }
}
