{-# LANGUAGE UnicodeSyntax #-}
{-# LANGUAGE TypeApplications #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE OverloadedStrings #-}

module MatrixBot.Bot.SmokeTest
  ( startupSmokeTest
  ) where

import Data.Proxy (Proxy (Proxy))
import Control.Monad (void)
import Servant.API (AuthProtect)
import Servant.Client.Core (AuthenticatedRequest)
import qualified MatrixBot.Log as L
import qualified MatrixBot.MatrixApi as Api
import qualified MatrixBot.MatrixApi.Client as Api
import qualified MatrixBot.SharedTypes as T
import MatrixBot.Bot.BotM (BotM)


-- | A smoke test to run to check Matrix API can be called using current authentication.
--
-- Intended to be run at startup, before doing anything else.
startupSmokeTest
   BotM r m
   Api.MatrixApiClient
   AuthenticatedRequest (AuthProtect "access-token")
   m ()
startupSmokeTest :: forall r (m :: * -> *).
BotM r m =>
MatrixApiClient
-> AuthenticatedRequest (AuthProtect "access-token") -> m ()
startupSmokeTest MatrixApiClient
req AuthenticatedRequest (AuthProtect "access-token")
auth = do
  Text -> m ()
forall (m :: * -> *). (MonadLogger m, HasCallStack) => Text -> m ()
L.logDebug Text
"Running a some test to make sure the bot is authenticated and can make Matrix API calls…"

  m EventsResponse -> m ()
forall (f :: * -> *) a. Functor f => f a -> f ()
void (m EventsResponse -> m ()) -> m EventsResponse -> m ()
forall a b. (a -> b) -> a -> b
$ MatrixApiClient
-> forall api (m :: * -> *) a.
   (MonadIO m, MonadFail m, Show a, MonadThrow m, MonadLogger m,
    HasClient (Free ClientF) api, HasClient ClientM api) =>
   Proxy api
   -> (forall (clientM :: * -> *).
       HasClient clientM api =>
       Client clientM api -> clientM a)
   -> m a
Api.runMatrixApiClient' MatrixApiClient
req (forall t. Proxy t
forall {k} (t :: k). Proxy t
Proxy @Api.EventsApi) ((forall {clientM :: * -> *}.
  HasClient clientM EventsApi =>
  Client clientM EventsApi -> clientM EventsResponse)
 -> m EventsResponse)
-> (forall {clientM :: * -> *}.
    HasClient clientM EventsApi =>
    Client clientM EventsApi -> clientM EventsResponse)
-> m EventsResponse
forall a b. (a -> b) -> a -> b
$ \Client clientM EventsApi
f  Client clientM EventsApi
AuthenticatedRequest (AuthProtect "access-token")
-> Maybe EventToken
-> Maybe RoomId
-> Maybe Milliseconds
-> clientM EventsResponse
f
    AuthenticatedRequest (AuthProtect "access-token")
auth
    Maybe EventToken
forall a. Maybe a
Nothing
    Maybe RoomId
forall a. Maybe a
Nothing
    (Milliseconds -> Maybe Milliseconds
forall a. a -> Maybe a
Just (Milliseconds -> Maybe Milliseconds)
-> (Integer -> Milliseconds) -> Integer -> Maybe Milliseconds
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Integer -> Milliseconds
T.Milliseconds (Integer -> Maybe Milliseconds) -> Integer -> Maybe Milliseconds
forall a b. (a -> b) -> a -> b
$ Integer
1)
    -- ↑ Timeouts as fast as possible (the list of received events would most likely be empty)