package com.ustadmobile.core.db.dao

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

@Dao
public actual abstract class ContentCategorySchemaDao : BaseDao<ContentCategorySchema> {
  @Query(`value` =
      "\n     REPLACE INTO ContentCategorySchemaReplicate(ccsPk, ccsDestination)\n      SELECT DISTINCT ContentCategorySchema.contentCategorySchemaUid AS ccsPk,\n             :newNodeId AS ccsDestination\n        FROM ContentCategorySchema\n       WHERE ContentCategorySchema.contentCategorySchemaLct != COALESCE(\n             (SELECT ccsVersionId\n                FROM ContentCategorySchemaReplicate\n               WHERE ccsPk = ContentCategorySchema.contentCategorySchemaUid\n                 AND ccsDestination = :newNodeId), 0) \n      /*psql ON CONFLICT(ccsPk, ccsDestination) DO UPDATE\n             SET ccsPending = true\n      */       \n    ")
  public actual abstract suspend fun replicateOnNewNode(newNodeId: Long): Unit

  @Query(`value` =
      "\n REPLACE INTO ContentCategorySchemaReplicate(ccsPk, ccsDestination)\n  SELECT DISTINCT ContentCategorySchema.contentCategorySchemaUid AS ccsUid,\n         UserSession.usClientNodeId AS ccsDestination\n    FROM ChangeLog\n         JOIN ContentCategorySchema\n             ON ChangeLog.chTableId = 2\n                AND ChangeLog.chEntityPk = ContentCategorySchema.contentCategorySchemaUid\n         JOIN UserSession ON UserSession.usStatus = 1\n   WHERE UserSession.usClientNodeId != (\n         SELECT nodeClientId \n           FROM SyncNode\n          LIMIT 1)\n     AND ContentCategorySchema.contentCategorySchemaLct != COALESCE(\n         (SELECT ccsVersionId\n            FROM ContentCategorySchemaReplicate\n           WHERE ccsPk = ContentCategorySchema.contentCategorySchemaUid\n             AND ccsDestination = UserSession.usClientNodeId), 0)\n /*psql ON CONFLICT(ccsPk, ccsDestination) DO UPDATE\n     SET ccsPending = true\n  */               \n    ")
  public actual abstract suspend fun replicateOnChange(): Unit

  @Query(`value` = "SELECT ContentCategorySchema.* FROM ContentCategorySchema")
  public actual abstract fun publicContentCategorySchemas(): List<ContentCategorySchema>

  @Query(`value` = "SELECT * FROM ContentCategorySchema WHERE schemaUrl = :schemaUrl")
  public actual abstract fun findBySchemaUrl(schemaUrl: String): ContentCategorySchema?
}
