module Jerimum.Tests.Integration.Helper
  ( runAndRead
  , runAndTest
  , executeAndTest
  , executeAndRead
  , executeArgsAndTest
  ) where

import           Control.Monad
import qualified Database.PostgreSQL.Simple as PQ
import           Jerimum.PostgreSQL
import           Jerimum.PostgreSQL.Types
import           Test.Tasty.HUnit

resultToMaybe :: Result a -> Maybe a
resultToMaybe (Success a) = Just a
resultToMaybe _           = Nothing

runAndRead :: Handle -> IO () -> IO (Maybe Event)
runAndRead handle runQuery =
  runQuery >> (resultToMaybe <$> recvFeedNoEmpty (pure True) handle)

runAndTest :: Handle -> IO () -> [TxData] -> IO ()
runAndTest handle runQuery expects = do
  mevent <- runAndRead handle runQuery
  (show . viewTxData . transaction <$> mevent) @?= Just (show expects)

executeArgsAndTest ::
     (PQ.ToRow q)
  => Handle
  -> PQ.Connection
  -> PQ.Query
  -> q
  -> [TxData]
  -> IO ()
executeArgsAndTest handle conn query args =
  runAndTest handle (void $ PQ.execute conn query args)

executeAndTest :: Handle -> PQ.Connection -> PQ.Query -> [TxData] -> IO ()
executeAndTest handle conn query =
  runAndTest handle (void $ PQ.execute_ conn query)

executeAndRead :: Handle -> PQ.Connection -> PQ.Query -> IO (Maybe Event)
executeAndRead handle conn query =
  runAndRead handle (void $ PQ.execute_ conn query)
