package com.ustadmobile.core.db.dao

import androidx.room.Dao
import androidx.room.Insert
import androidx.room.Query
import com.ustadmobile.lib.db.entities.ContentEntryVersion
import kotlin.Any
import kotlin.Int
import kotlin.Long
import kotlin.collections.List
import kotlinx.coroutines.flow.Flow

@Dao
public actual abstract class ContentEntryVersionDao {
  @Query(`value` =
      "\n        SELECT ContentEntryVersion.*\n          FROM ContentEntryVersion\n         WHERE cevUid = :cevUid \n    ")
  public actual abstract suspend fun findByUidAsync(cevUid: Long): ContentEntryVersion?

  @Insert(
    entity = Any::class,
    onConflict = 3,
  )
  public actual abstract suspend fun insertAsync(contentEntryVersion: ContentEntryVersion): Long

  @Query(`value` =
      "\n        SELECT ContentEntryVersion.*\n          FROM ContentEntryVersion\n         WHERE ContentEntryVersion.cevContentEntryUid = :contentEntryUid\n      ORDER BY ContentEntryVersion.cevLastModified DESC\n         LIMIT 1\n    ")
  public actual abstract suspend
      fun findLatestVersionUidByContentEntryUidEntity(contentEntryUid: Long): ContentEntryVersion?

  @Query(`value` =
      "\n        SELECT ContentEntryVersion.*\n          FROM ContentEntryVersion\n         WHERE ContentEntryVersion.cevContentEntryUid = :contentEntryUid\n      ORDER BY ContentEntryVersion.cevLastModified DESC\n         LIMIT 1\n    ")
  public actual abstract fun findLatestByContentEntryUidAsFlow(contentEntryUid: Long):
      Flow<ContentEntryVersion?>

  @Query(`value` =
      "\n        UPDATE TransferJobItem\n           SET tjiEntityEtag = \n               (SELECT cevLct\n                  FROM ContentEntryVersion\n                 WHERE cevUid = :entityUid)\n         WHERE tjiUid = :transferJobItemUid\n    ")
  public actual abstract suspend fun updateTransferJobItemEtag(entityUid: Long,
      transferJobItemUid: Int)

  @Query(`value` =
      "\n        SELECT ContentEntryVersion.*\n          FROM ContentEntryVersion\n         WHERE NOT EXISTS(\n               SELECT CacheLockJoin.cljId\n                 FROM CacheLockJoin\n                WHERE CacheLockJoin.cljTableId = 738\n                  AND CacheLockJoin.cljEntityUid = ContentEntryVersion.cevUid\n                  AND CacheLockJoin.cljUrl = ContentEntryVersion.cevManifestUrl) \n    ")
  public actual abstract suspend fun findContentEntryVersionsWithoutCacheLock():
      List<ContentEntryVersion>
}
