package com.ustadmobile.core.db.dao

import androidx.paging.PagingSource
import androidx.room.Dao
import androidx.room.Insert
import androidx.room.Query
import androidx.room.Update
import com.ustadmobile.lib.db.composites.ClazzInviteAndClazz
import com.ustadmobile.lib.db.composites.ClazzInviteWithTimeZone
import com.ustadmobile.lib.db.entities.ClazzInvite
import kotlin.Any
import kotlin.Int
import kotlin.Long
import kotlin.String
import kotlin.collections.List
import kotlinx.coroutines.flow.Flow

@Dao
public actual abstract class ClazzInviteDao : BaseDao<ClazzInvite> {
  @Insert(
    onConflict = 1,
    entity = Any::class,
  )
  public actual abstract suspend fun replace(entity: ClazzInvite): Long

  @Insert(
    onConflict = 5,
    entity = Any::class,
  )
  public actual abstract suspend fun insertAll(entity: List<ClazzInvite>)

  @Update(
    onConflict = 5,
    entity = Any::class,
  )
  public actual abstract suspend fun updateAll(entity: List<ClazzInvite>)

  @Query(`value` = "SELECT * FROM ClazzInvite")
  public actual abstract suspend fun findInviteAsync(): List<ClazzInvite>

  @Query(`value` =
      "\n    SELECT ClazzInvite.*, \n           COALESCE(Clazz.clazzTimeZone, 'UTC') AS timeZone\n      FROM ClazzInvite\n           LEFT JOIN Clazz \n                     ON Clazz.clazzUid = ClazzInvite.ciClazzUid\n     WHERE ClazzInvite.inviteToken = :inviteTokenUid\n")
  public actual abstract suspend fun findClazzInviteEntityForInviteToken(inviteTokenUid: String):
      ClazzInviteWithTimeZone?

  @Query(`value` =
      "\n    SELECT ClazzInvite.*, Clazz.*\n      FROM ClazzInvite\n           JOIN Clazz \n                ON Clazz.clazzUid = ClazzInvite.ciClazzUid\n     WHERE ClazzInvite.inviteToken = :inviteTokenUid\n    ")
  public actual abstract fun findClazzInviteEntityForInviteTokenAsFlow(inviteTokenUid: String):
      Flow<ClazzInviteAndClazz?>

  @Query(`value` =
      "\n        UPDATE ClazzInvite \n           SET inviteStatus = :status,\n               inviteLct = :updateTime\n         WHERE ClazzInvite.ciUid =:ciUid\n    ")
  public actual abstract suspend fun updateInviteStatus(
    status: Int,
    ciUid: Long,
    updateTime: Long,
  )

  @Query(`value` =
      "SELECT * FROM ClazzInvite \n                 WHERE ciPersonUid = :ciPersonUid AND ciClazzUid = :clazzUid \n              AND inviteExpire > :currentTime AND inviteStatus = 0")
  public actual abstract fun findPendingInviteByPersonUid(
    ciPersonUid: Long,
    clazzUid: Long,
    currentTime: Long,
  ): PagingSource<Int, ClazzInvite>

  @Query(`value` =
      "\n        UPDATE ClazzInvite \n          SET inviteStatus = 3\n        WHERE inviteContact = :inviteContact")
  public actual abstract suspend fun updateClazzInviteToRevokeInvite(inviteContact: String): Int

  @Query(`value` = "SELECT * FROM ClazzInvite WHERE inviteContact = :inviteContact")
  public actual abstract suspend fun findClazzInviteFromContact(inviteContact: String): ClazzInvite?
}
