{-# LANGUAGE NoImplicitPrelude #-}

module Data.Morpheus.Parser
  ( parseSchema,
    parseTypeDefinitions,
    parseDefinitions,
    parseRequest,
    parseRequestWith,
  )
where

import Data.ByteString.Lazy (ByteString)
import Data.Morpheus.Ext.Result
  ( GQLResult,
    sortErrors,
  )
import Data.Morpheus.Internal.Utils ((<:>))
import Data.Morpheus.Parsing.Document.TypeSystem
  ( parseDefinitions,
    parseTypeDefinitions,
  )
import qualified Data.Morpheus.Parsing.Document.TypeSystem as P
  ( parseSchema,
  )
import Data.Morpheus.Parsing.Request.Parser
  ( parseRequest,
  )
import Data.Morpheus.Schema.Schema (internalSchema)
import Data.Morpheus.Types.IO
  ( GQLRequest (..),
  )
import Data.Morpheus.Types.Internal.AST
  ( Operation,
    Schema (..),
    VALID,
  )
import Data.Morpheus.Types.Internal.Config
  ( Config (..),
    VALIDATION_MODE (..),
  )
import Data.Morpheus.Validation.Document.Validation
  ( validateSchema,
  )
import Data.Morpheus.Validation.Query.Validation
  ( validateRequest,
  )
import Relude hiding (ByteString)

parseSchema ::
  ByteString -> GQLResult (Schema VALID)
parseSchema :: ByteString -> GQLResult (Schema VALID)
parseSchema =
  forall a. Result GQLError a -> Result GQLError a
sortErrors
    forall b c a. (b -> c) -> (a -> b) -> a -> c
. ( ByteString -> GQLResult (Schema CONST)
P.parseSchema
          forall (m :: * -> *) a b c.
Monad m =>
(a -> m b) -> (b -> m c) -> a -> m c
>=> forall (s :: Stage).
ValidateSchema s =>
Bool -> Config -> Schema s -> GQLResult (Schema VALID)
validateSchema
            Bool
True
            Config
              { debug :: Bool
debug = Bool
False,
                validationMode :: VALIDATION_MODE
validationMode = VALIDATION_MODE
FULL_VALIDATION
              }
      )

parseRequestWith :: Config -> Schema VALID -> GQLRequest -> GQLResult (Operation VALID)
parseRequestWith :: Config -> Schema VALID -> GQLRequest -> GQLResult (Operation VALID)
parseRequestWith Config
config Schema VALID
schema GQLRequest
req = do
  ExecutableDocument
qu <- GQLRequest -> GQLResult ExecutableDocument
parseRequest GQLRequest
req
  Schema VALID
fillSchema <- forall (s :: Stage). Schema s
internalSchema forall (m :: * -> *) a.
(Merge (HistoryT m) a, Monad m) =>
a -> a -> m a
<:> Schema VALID
schema
  Config
-> Schema VALID
-> ExecutableDocument
-> GQLResult (Operation VALID)
validateRequest Config
config Schema VALID
fillSchema ExecutableDocument
qu