package de.sebse.fuplanner2.database

import androidx.room.*

@Dao
interface UserDao {
    @Query("SELECT * FROM user")
    fun getAll(): List<User>

    @Query("SELECT * FROM user WHERE uid IN (:userIds)")
    fun loadAllByIds(userIds: IntArray): List<User>

    @Query("SELECT * FROM user WHERE first_name LIKE :first AND last_name LIKE :last LIMIT 1")
    fun findByName(first: String, last: String): User?

    @Query("SELECT * FROM user WHERE username LIKE :name LIMIT 1")
    fun findByUsername(name: String): User?

    @Insert(onConflict = OnConflictStrategy.IGNORE)
    fun insert(user: User): Long

    @Update(onConflict = OnConflictStrategy.REPLACE)
    fun update(user: User)

    @Transaction
    fun upsert(user: User) {
        val id = insert(user)
        if (id == -1L) {
            update(user)
        } else {
            user.uid = id
        }
    }

    @Delete
    fun delete(user: User)

    @Query("DELETE FROM user WHERE username = :userName")
    fun deleteByUserName(userName: String)

}