package com.ustadmobile.core.db.dao

import androidx.room.Dao
import androidx.room.Insert
import androidx.room.Query
import com.ustadmobile.lib.db.entities.ExternalAppPermission
import kotlin.Any
import kotlin.Int
import kotlin.Long
import kotlin.String

@Dao
public actual abstract class ExternalAppPermissionDao {
  @Insert(
    entity = Any::class,
    onConflict = 3,
  )
  public actual abstract suspend fun insertAsync(externalAppPermission: ExternalAppPermission): Long

  @Query(`value` =
      "\n        SELECT ExternalAppPermission.eapAuthToken\n          FROM ExternalAppPermission\n         WHERE ExternalAppPermission.eapPackageId = :packageId\n           AND ExternalAppPermission.eapPersonUid = :personUid\n           AND :currentTime BETWEEN ExternalAppPermission.eapStartTime AND ExternalAppPermission.eapExpireTime\n         LIMIT 1  \n    ")
  public actual abstract suspend fun getGrantedAuthToken(
    packageId: String,
    personUid: Long,
    currentTime: Long,
  ): String?

  @Query(`value` =
      "\n        SELECT *\n          FROM ExternalAppPermission\n         WHERE eapUid = :eapUid \n    ")
  public actual abstract suspend fun getExternalAccessPermissionByUid(eapUid: Int):
      ExternalAppPermission?

  @Query(`value` =
      "\n        SELECT COALESCE(\n               (SELECT eapPersonUid\n                  FROM ExternalAppPermission\n                 WHERE eapAuthToken = :token\n                   AND :currentTime BETWEEN eapStartTime AND eapExpireTime\n               ),\n               0)    \n    ")
  public actual abstract suspend fun getPersonUidByAuthToken(token: String, currentTime: Long): Long
}
