{-# LANGUAGE MultiParamTypeClasses #-}

module Web.JWT.ASAP.Env (
  MonadEnv (..)
, asapLookupEnv
) where

import           Control.Lens         (( # ))
import           Control.Monad.Except (ExceptT, MonadError (..))
import           Control.Monad.Trans  (lift)
import           System.Environment   (lookupEnv)
import           Web.JWT.ASAP.Error

class MonadEnv m where
  lookupEnv' :: String -> m (Maybe String)

instance MonadEnv IO where
  lookupEnv' =
    lookupEnv

instance (Monad m, MonadEnv m) => MonadEnv (ExceptT e m) where
  lookupEnv' =
    lift . lookupEnv'

asapLookupEnv :: (MonadError e m, HasAsapError e, MonadEnv m) => String -> m String
asapLookupEnv s =
  maybe (throwError (asapMissingEnv # s)) pure =<< lookupEnv' s