package com.ustadmobile.core.db.dao

import androidx.room.Dao
import androidx.room.Insert
import androidx.room.Query
import androidx.room.Update
import com.ustadmobile.lib.db.entities.Site
import kotlin.Long
import kotlin.String
import kotlin.Unit

@Dao
public actual abstract class SiteDao {
  @Query(`value` = "SELECT * FROM Site LIMIT 1")
  public actual abstract fun getSite(): Site?

  @Query(`value` = "SELECT * FROM Site LIMIT 1")
  public actual abstract suspend fun getSiteAsync(): Site?

  @Query(`value` = "SELECT authSalt FROM Site LIMIT 1")
  public actual abstract suspend fun getSiteAuthSaltAsync(): String?

  @Insert(onConflict = 1)
  public actual abstract suspend fun replaceAsync(site: Site): Long

  @Insert(onConflict = 3)
  public actual abstract fun insert(site: Site): Long

  @Update(onConflict = 3)
  public actual abstract suspend fun updateAsync(workspace: Site): Unit

  @Query(`value` =
      "\n        REPLACE INTO SiteReplicate(sitePk, siteDestination)\n         SELECT DISTINCT Site.siteUid AS sitePk,\n                :newNodeId AS siteDestination\n           FROM Site\n          WHERE Site.siteLct != COALESCE(\n                (SELECT siteVersionId\n                   FROM SiteReplicate\n                  WHERE sitePk = Site.siteUid\n                    AND siteDestination = :newNodeId), 0) \n         /*psql ON CONFLICT(sitePk, siteDestination) DO UPDATE\n                SET sitePending = true\n         */       \n    ")
  public actual abstract suspend fun replicateOnNewNode(newNodeId: Long): Unit

  @Query(`value` =
      "\n        REPLACE INTO SiteReplicate(sitePk, siteDestination)\n         SELECT DISTINCT Site.siteUid AS sitePk,\n                UserSession.usClientNodeId AS siteDestination\n           FROM ChangeLog\n                JOIN Site \n                    ON ChangeLog.chTableId = 189 \n                       AND ChangeLog.chEntityPk = Site.siteUid\n                JOIN UserSession ON UserSession.usStatus = 1\n          WHERE UserSession.usClientNodeId != (\n                SELECT nodeClientId \n                  FROM SyncNode\n                 LIMIT 1)\n            AND Site.siteLct != COALESCE(\n                (SELECT siteVersionId\n                   FROM SiteReplicate\n                  WHERE sitePk = Site.siteUid\n                    AND siteDestination = UserSession.usClientNodeId), 0)     \n        /*psql  ON CONFLICT(sitePk, siteDestination) DO UPDATE\n            SET sitePending = true\n         */               \n    ")
  public actual abstract suspend fun replicateOnChange(): Unit
}
