package com.ustadmobile.core.db.dao

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

@Dao
public actual abstract class ErrorReportDao {
  @Query(`value` =
      "\n REPLACE INTO ErrorReportReplicate(erPk, erDestination)\n  SELECT DISTINCT ErrorReport.errUid AS erUid,\n           UserSession.usClientNodeId AS erDestination\n    FROM ChangeLog\n         JOIN ErrorReport\n             ON ChangeLog.chTableId = 419\n                AND ChangeLog.chEntityPk = ErrorReport.errUid\n         JOIN UserSession ON UserSession.usSessionType = 2\n    WHERE UserSession.usClientNodeId != (\n         SELECT nodeClientId \n           FROM SyncNode\n          LIMIT 1)\n     AND ErrorReport.errLct != COALESCE(\n         (SELECT erVersionId\n            FROM ErrorReportReplicate\n           WHERE erPk = ErrorReport.errUid\n             AND erDestination = UserSession.usClientNodeId), 0)\n    /*psql ON CONFLICT(erPk, erDestination) DO UPDATE\n     SET erPending = true\n    */               \n    ")
  public actual abstract suspend fun replicateOnChange(): Unit

  @Insert(onConflict = 3)
  public actual abstract suspend fun insertAsync(errorReport: ErrorReport): Long

  @Query(`value` =
      "\n        SELECT ErrorReport.* \n          FROM ErrorReport\n         WHERE errUid = :errUid\n    ")
  public actual abstract suspend fun findByUidAsync(errUid: Long): ErrorReport?

  @Query(`value` =
      "\n        SELECT ErrorReport.*\n          FROM ErrorReport\n         WHERE errorCode = :errCode  \n    ")
  public actual abstract suspend fun findByErrorCode(errCode: Int): List<ErrorReport>
}
