package com.ustadmobile.core.db.dao

import androidx.room.Dao
import androidx.room.Query
import androidx.room.Update
import com.ustadmobile.lib.db.entities.PersonGroup
import kotlin.Any
import kotlin.Int
import kotlin.Long
import kotlin.String
import kotlinx.coroutines.flow.Flow

@Dao
public actual abstract class PersonGroupDao : BaseDao<PersonGroup> {
  @Query(`value` = "SELECT * FROM PersonGroup WHERE groupUid = :uid")
  public actual abstract fun findByUid(uid: Long): PersonGroup?

  @Query(`value` = "SELECT * FROM PersonGroup WHERE groupUid = :uid")
  public actual abstract suspend fun findByUidAsync(uid: Long): PersonGroup?

  @Query(`value` = "SELECT * FROM PersonGroup WHERE groupUid = :uid")
  public actual abstract fun findByUidLive(uid: Long): Flow<PersonGroup?>

  @Update(
    entity = Any::class,
    onConflict = 3,
  )
  public actual abstract suspend fun updateAsync(entity: PersonGroup): Int

  @Query(`value` =
      "\n        Select CASE\n               WHEN Person.firstNames IS NOT NULL THEN Person.firstNames\n               ELSE PersonGroup.groupName \n               END AS name\n          FROM PersonGroup\n               LEFT JOIN Person\n                         ON Person.personGroupUid = PersonGroup.groupUid\n         WHERE PersonGroup.groupUid = :groupUid\n         LIMIT 1\n    ")
  public actual abstract suspend fun findNameByGroupUid(groupUid: Long): String?
}
