package com.ustadmobile.core.db.dao.xapi

import androidx.room.Dao
import androidx.room.Insert
import androidx.room.Query
import com.ustadmobile.lib.db.entities.xapi.XapiSessionEntity
import kotlin.Any
import kotlin.Boolean
import kotlin.Long

@Dao
public actual abstract class XapiSessionEntityDao {
  @Insert(
    entity = Any::class,
    onConflict = 3,
  )
  public actual abstract suspend fun insertAsync(xapiSessionEntity: XapiSessionEntity)

  @Query(`value` =
      "\n        SELECT XapiSessionEntity.*\n          FROM XapiSessionEntity\n         WHERE XapiSessionEntity.xseUid = :uid\n    ")
  public actual abstract suspend fun findByUidAsync(uid: Long): XapiSessionEntity?

  @Query(`value` =
      "\n        UPDATE XapiSessionEntity\n           SET xseCompleted = :completed,\n               xseLastMod = :time\n         WHERE xseUid = :xseUid\n\n    ")
  public actual abstract suspend fun updateLatestAsComplete(
    completed: Boolean,
    time: Long,
    xseUid: Long,
  )

  @Query(`value` =
      "\n        SELECT XapiSessionEntity.*\n          FROM XapiSessionEntity\n         WHERE XapiSessionEntity.xseRootActivityUid = :xseRootActivityUid\n           AND XapiSessionEntity.xseActorUid = :actorUid\n           AND XapiSessionEntity.xseContentEntryVersionUid = :contentEntryVersionUid\n           AND XapiSessionEntity.xseClazzUid = :clazzUid\n           AND EXISTS(\n               SELECT 1\n                 FROM ActorEntity\n                WHERE ActorEntity.actorUid = :actorUid\n                  AND ActorEntity.actorPersonUid = :accountPersonUid)     \n    ")
  public actual abstract suspend fun findMostRecentSessionByActorAndActivity(
    accountPersonUid: Long,
    actorUid: Long,
    xseRootActivityUid: Long,
    contentEntryVersionUid: Long,
    clazzUid: Long,
  ): XapiSessionEntity?
}
