{-# LANGUAGE OverloadedStrings #-}

module Main where

import           Control.Monad (unless, void)
import           Data.Text     (Text)
import           Hedgehog
import           System.Exit   (exitFailure)
import           System.IO     (BufferMode (..), hSetBuffering, stderr, stdout)
import qualified Web.JWT       as JWT
import           Web.JWT.ASAP

import           Util

isExpiredProp :: Property
isExpiredProp =
  property $ do
    maxAge@(MaxAge maxAgeTime) <- forAll genMaxAge
    iat <- forAll genInDecade
    -- numericDate rounds so we have to + 1 to make a later time
    assert $ maybe False (\iat' -> laterThanMaxAge maxAge iat' (iat + maxAgeTime + 1)) (JWT.numericDate iat)

asapSignerFromEnvProp :: Property
asapSignerFromEnvProp =
  withTests 1 . property $ do
    let signer = runWithEnv asapSignerFromEnv [("ASAP_PRIVATE_KEY", exampleDataUri)]
    void signer === Right ()

asapAuthHeaderFromEnvProp :: Property
asapAuthHeaderFromEnvProp =
  withTests 1 . property $ do
    let env = [ ("ASAP_PRIVATE_KEY", exampleDataUri)
              , ("ASAP_ISSUER", "haskell-asap")
              , ("ASAP_KEY_ID", "haskell-asap-demo1")
              ]
        header = runWithEnv (asapAuthHeaderFromEnv mempty mempty) env
    header === Right ("Bearer " <> emptyClaimHeader)

emptyClaimHeader :: Text
emptyClaimHeader =
  "eyJhbGciOiJSUzI1NiIsImtpZCI6Imhhc2tlbGwtYXNhcC1kZW1vMSIsInR5cCI6IkpXVCJ9.eyJpc3M\
  \iOiJoYXNrZWxsLWFzYXAifQ.E95y64Fc42ulqZ--3jClZiPqXJiaOCucceJwJLFWaBYA7Evlb7fhLGy-\
  \QJTzZ7_nHTfK6omspCObPT2DA-KNNT63DjShsW5cZjyCB2zMhtnWFB63wttlIoxs7EePBI8QpmdNcCTt\
  \cokMIL0yULSE-9BZaPehs38yo71fHH3Zzk9LLnPf76FkuTsCmKi26NcL2WcQV3tSrHro1upyGq3i29dt\
  \60dkokO6plCXQFq_CNfNneytUWg0LpqJhPCO0pAiiVedEjobi8tHdJgNzD81v-QgBPr2k1eqnMtYMjzs\
  \wq_g-HxCO_rtjrgGBhcovRvIZm1-ssAJVg9JA9cGGdxq_Q"

main :: IO ()
main = do
  hSetBuffering stdout LineBuffering
  hSetBuffering stderr LineBuffering

  results <- checkParallel $
    Group "ASAP" [ ("laterThanMaxAge", isExpiredProp)
                 , ("asapSignerFromEnv", asapSignerFromEnvProp)
                 , ("asapAuthHeaderFromEnvProp", asapAuthHeaderFromEnvProp)
                 ]

  unless results exitFailure
