// Copyright (c) 2025 Gleb Zaharov. License: GPLv3 (see LICENSE).

package ru.sweetbread.unn.db

import android.util.Log
import androidx.room.ColumnInfo
import androidx.room.Dao
import androidx.room.Delete
import androidx.room.Entity
import androidx.room.Insert
import androidx.room.PrimaryKey
import androidx.room.Query
import ru.sweetbread.unn.api.AvatarSet
import ru.sweetbread.unn.api.Type
import ru.sweetbread.unn.api.User
import java.time.LocalDate
import java.time.LocalDateTime
import java.time.format.DateTimeFormatter

@Entity
data class UserDB(
    @PrimaryKey val userId: Int,
    @ColumnInfo val unnId: Int?,
    @ColumnInfo val type: Type,
    @ColumnInfo val email: String,
    @ColumnInfo val nameRu: String,
    @ColumnInfo val nameEn: String,
    @ColumnInfo val isMale: Boolean,
    @ColumnInfo val birthday: String,
    @ColumnInfo val origAvatar: String,
    @ColumnInfo val thumbAvatar: String,
    @ColumnInfo val smallAvatar: String,
    @ColumnInfo val expiredAt: String
)

@Dao
interface UserDao {
    @Query("SELECT * FROM userDB WHERE userId = :userId LIMIT 1")
    fun getUserById(userId: Int): UserDB?

    @Insert
    fun insert(user: UserDB)

    @Delete
    fun delete(user: UserDB)
}


fun cacheUser(user: User) {
    try {
        cacheDb.userDao().insert(
            UserDB(
                user.userId,
                user.unnId,
                user.type,
                user.email,
                user.nameRu,
                user.nameEn,
                user.isMale,
                user.birthday.format(DateTimeFormatter.ISO_LOCAL_DATE),
                user.avatar.original,
                user.avatar.thumbnail,
                user.avatar.small,
                LocalDateTime.now().plusDays(1).format(DateTimeFormatter.ISO_LOCAL_DATE_TIME)
            )
        )
    } catch (_: android.database.sqlite.SQLiteConstraintException) {
    }
}

fun loadUserByBitrixId(bitrixId: Int): User? {
    val user = cacheDb.userDao().getUserById(bitrixId)
    Log.d("UserDB", user?.nameEn ?: "None")
    if (user == null) return null
    if (LocalDateTime.parse(
            user.expiredAt,
            DateTimeFormatter.ISO_LOCAL_DATE_TIME
        ) < LocalDateTime.now()
    ) {
        cacheDb.userDao().delete(user)
        return null
    } else {
        return User(
            user.unnId,
            user.userId,
            user.type,
            user.email,
            user.nameRu,
            user.nameEn,
            user.isMale,
            LocalDate.parse(user.birthday, DateTimeFormatter.ISO_LOCAL_DATE),
            AvatarSet(
                user.origAvatar,
                user.thumbAvatar,
                user.smallAvatar
            )
        )
    }
}