{-# LANGUAGE OverloadedStrings    #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
module Config where

import            Control.Monad.Except  (ExceptT(..))
import            Data.Aeson
import qualified  Data.Text             as TS
import            Data.Yaml
import            Network.URI           (URI, parseURI)
import            Web.JWT

data Config = Config { port :: Int
                     , authDBPath :: FilePath
                     , logPath :: FilePath
                     , baseUrl :: URI
                     , jwtSecret :: Secret
                     } deriving (Show)


instance FromJSON Config where
  parseJSON (Object obj) =
    Config <$> obj .: "port"
           <*> obj .: "auth-db-path"
           <*> obj .: "log-path"
           <*> obj .: "base-url"
           <*> (secret <$> obj .: "jwt-secret")
  parseJSON _ = mempty

instance FromJSON URI where
  parseJSON (String str) = maybe mempty pure (parseURI $ TS.unpack str)
  parseJSON _ = mempty

loadConfig :: FilePath -> ExceptT ParseException IO Config
loadConfig = ExceptT . decodeFileEither
