package com.github.nullptroma.wallenc.infrastructure.android.db.app.model

import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.PrimaryKey
import com.github.nullptroma.wallenc.domain.vault.model.StorageKeyMap
import com.github.nullptroma.wallenc.domain.datatypes.EncryptKey
import java.util.UUID

@Entity(tableName = "storage_key_maps")
data class DbStorageKeyMap(
    @PrimaryKey
    @ColumnInfo(name = "source_uuid") val sourceUuid: UUID,
    @ColumnInfo(name = "key") val key: ByteArray
) {
    fun toModel(): StorageKeyMap {
        return StorageKeyMap(
            sourceUuid = sourceUuid,
            key = EncryptKey(key)
        )
    }

    override fun equals(other: Any?): Boolean {
        if (this === other) return true
        if (javaClass != other?.javaClass) return false

        other as DbStorageKeyMap

        if (sourceUuid != other.sourceUuid) return false
        if (!key.contentEquals(other.key)) return false

        return true
    }

    override fun hashCode(): Int {
        var result = sourceUuid.hashCode()
        result = 31 * result + key.contentHashCode()
        return result
    }

    companion object {
        fun fromModel(keymap: StorageKeyMap): DbStorageKeyMap {
            return DbStorageKeyMap(
                sourceUuid = keymap.sourceUuid,
                key = keymap.key.bytes
            )
        }
    }
}
