package com.ustadmobile.core.db.dao

import androidx.room.Dao
import androidx.room.Query
import com.ustadmobile.lib.db.entities.StateContentEntity
import kotlin.Boolean
import kotlin.Long
import kotlin.String
import kotlin.Unit
import kotlin.collections.List

@Dao
public actual abstract class StateContentDao : BaseDao<StateContentEntity> {
  @Query(`value` =
      "\n     REPLACE INTO StateContentEntityReplicate(scePk, sceDestination)\n      SELECT DISTINCT StateContentEntity.stateContentUid AS scePk,\n             :newNodeId AS sceDestination\n        FROM StateContentEntity\n       WHERE StateContentEntity.stateContentLct != COALESCE(\n             (SELECT sceVersionId\n                FROM StateContentEntityReplicate\n               WHERE scePk = StateContentEntity.stateContentUid\n                 AND sceDestination = :newNodeId), 0) \n      /*psql ON CONFLICT(scePk, sceDestination) DO UPDATE\n             SET scePending = true\n      */       \n    ")
  public actual abstract suspend fun replicateOnNewNode(newNodeId: Long): Unit

  @Query(`value` =
      "\n REPLACE INTO StateContentEntityReplicate(scePk, sceDestination)\n  SELECT DISTINCT StateContentEntity.stateContentUid AS sceUid,\n         UserSession.usClientNodeId AS sceDestination\n    FROM ChangeLog\n         JOIN StateContentEntity\n             ON ChangeLog.chTableId = 72\n                AND ChangeLog.chEntityPk = StateContentEntity.stateContentUid\n         JOIN UserSession ON UserSession.usStatus = 1\n   WHERE UserSession.usClientNodeId != (\n         SELECT nodeClientId \n           FROM SyncNode\n          LIMIT 1)\n     AND StateContentEntity.stateContentLct != COALESCE(\n         (SELECT sceVersionId\n            FROM StateContentEntityReplicate\n           WHERE scePk = StateContentEntity.stateContentUid\n             AND sceDestination = UserSession.usClientNodeId), 0)\n /*psql ON CONFLICT(scePk, sceDestination) DO UPDATE\n     SET scePending = true\n  */               \n ")
  public actual abstract suspend fun replicateOnChange(): Unit

  @Query(`value` =
      "SELECT * FROM StateContentEntity WHERE stateContentStateUid = :id AND isIsactive")
  public actual abstract fun findAllStateContentWithStateUid(id: Long): List<StateContentEntity>

  @Query(`value` =
      "SELECT * FROM StateContentEntity WHERE stateContentStateUid = :stateUid AND stateContentKey = :key AND isIsactive")
  public actual abstract fun findStateContentByKeyAndStateUid(key: String, stateUid: Long):
      StateContentEntity?

  @Query(`value` =
      "\n        UPDATE StateContentEntity \n           SET isIsactive = :isActive,  \n               stateContentLct = :updateTime\n         WHERE stateContentUid = :stateUid\n    ")
  public actual abstract fun setInActiveStateContentByKeyAndUid(
    isActive: Boolean,
    stateUid: Long,
    updateTime: Long,
  ): Unit
}
