package com.ustadmobile.core.db.dao

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

@Dao
public actual abstract class ContentEntryContentCategoryJoinDao :
    BaseDao<ContentEntryContentCategoryJoin> {
  @Query(`value` =
      "\n     REPLACE INTO ContentEntryContentCategoryJoinReplicate(ceccjPk, ceccjDestination)\n      SELECT DISTINCT ContentEntryContentCategoryJoin.ceccjUid AS ceccjPk,\n             :newNodeId AS ceccjDestination\n        FROM ContentEntryContentCategoryJoin\n       WHERE ContentEntryContentCategoryJoin.ceccjLct != COALESCE(\n             (SELECT ceccjVersionId\n                FROM ContentEntryContentCategoryJoinReplicate\n               WHERE ceccjPk = ContentEntryContentCategoryJoin.ceccjUid\n                 AND ceccjDestination = :newNodeId), 0) \n      /*psql ON CONFLICT(ceccjPk, ceccjDestination) DO UPDATE\n             SET ceccjPending = true\n      */       \n    ")
  public actual abstract suspend fun replicateOnNewNode(newNodeId: Long): Unit

  @Query(`value` =
      "\n REPLACE INTO ContentEntryContentCategoryJoinReplicate(ceccjPk, ceccjDestination)\n  SELECT DISTINCT ContentEntryContentCategoryJoin.ceccjUid AS ceccjUid,\n         UserSession.usClientNodeId AS ceccjDestination\n    FROM ChangeLog\n         JOIN ContentEntryContentCategoryJoin\n             ON ChangeLog.chTableId = 3\n                AND ChangeLog.chEntityPk = ContentEntryContentCategoryJoin.ceccjUid\n         JOIN UserSession ON UserSession.usStatus = 1\n   WHERE UserSession.usClientNodeId != (\n         SELECT nodeClientId \n           FROM SyncNode\n          LIMIT 1)\n     AND ContentEntryContentCategoryJoin.ceccjLct != COALESCE(\n         (SELECT ceccjVersionId\n            FROM ContentEntryContentCategoryJoinReplicate\n           WHERE ceccjPk = ContentEntryContentCategoryJoin.ceccjUid\n             AND ceccjDestination = UserSession.usClientNodeId), 0)\n /*psql ON CONFLICT(ceccjPk, ceccjDestination) DO UPDATE\n     SET ceccjPending = true\n  */               \n    ")
  public actual abstract suspend fun replicateOnChange(): Unit

  @Query(`value` =
      "SELECT ContentEntryContentCategoryJoin.* FROM ContentEntryContentCategoryJoin LEFT JOIN ContentEntry ON ContentEntryContentCategoryJoin.ceccjContentEntryUid = ContentEntry.contentEntryUid WHERE ContentEntry.publik")
  public actual abstract fun publicContentEntryContentCategoryJoins():
      List<ContentEntryContentCategoryJoin>

  @Query(`value` =
      "SELECT * from ContentEntryContentCategoryJoin WHERE ceccjContentCategoryUid = :categoryUid AND ceccjContentEntryUid = :contentEntry")
  public actual abstract fun findJoinByParentChildUuids(categoryUid: Long, contentEntry: Long):
      ContentEntryContentCategoryJoin?
}
