package com.ustadmobile.core.db.dao

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

@Dao
public actual abstract class ContentCategoryDao : BaseDao<ContentCategory> {
  @Query(`value` =
      "\n     REPLACE INTO ContentCategoryReplicate(ccPk, ccDestination)\n      SELECT DISTINCT ContentCategory.contentCategoryUid AS ccPk,\n             :newNodeId AS ccDestination\n        FROM ContentCategory\n       WHERE ContentCategory.contentCategoryLct != COALESCE(\n             (SELECT ccVersionId\n                FROM ContentCategoryReplicate\n               WHERE ccPk = ContentCategory.contentCategoryUid\n                 AND ccDestination = :newNodeId), 0) \n      /*psql ON CONFLICT(ccPk, ccDestination) DO UPDATE\n             SET ccPending = true\n      */       \n    ")
  public actual abstract suspend fun replicateOnNewNode(newNodeId: Long): Unit

  @Query(`value` =
      "\n REPLACE INTO ContentCategoryReplicate(ccPk, ccDestination)\n  SELECT DISTINCT ContentCategory.contentCategoryUid AS ccUid,\n         UserSession.usClientNodeId AS ccDestination\n    FROM ChangeLog\n         JOIN ContentCategory\n             ON ChangeLog.chTableId = 1\n                AND ChangeLog.chEntityPk = ContentCategory.contentCategoryUid\n         JOIN UserSession \n              ON UserSession.usStatus = 1\n   WHERE UserSession.usClientNodeId != (\n         SELECT nodeClientId \n           FROM SyncNode\n          LIMIT 1)\n     AND ContentCategory.contentCategoryLct != COALESCE(\n         (SELECT ccVersionId\n            FROM ContentCategoryReplicate\n           WHERE ccPk = ContentCategory.contentCategoryUid\n             AND ccDestination = UserSession.usClientNodeId), 0)\n /*psql ON CONFLICT(ccPk, ccDestination) DO UPDATE\n     SET ccPending = true\n  */               \n    ")
  public actual abstract suspend fun replicateOnChange(): Unit

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

  @Query(`value` =
      "SELECT * FROM ContentCategory WHERE ctnCatContentCategorySchemaUid = :schemaId AND name = :name")
  public actual abstract fun findCategoryBySchemaIdAndName(schemaId: Long, name: String):
      ContentCategory?
}
