{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE NamedFieldPuns #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TupleSections #-}
{-# LANGUAGE NoImplicitPrelude #-}

module Data.Morpheus.Validation.Query.UnionSelection
  ( validateUnionSelection,
    validateInterfaceSelection,
  )
where

import qualified Data.HashMap.Lazy as HM
import Data.Mergeable (OrdMap)
import Data.Morpheus.Internal.Utils
  ( empty,
    fromElems,
    mergeConcat,
    selectOr,
    startHistory,
  )
import Data.Morpheus.Types.Internal.AST.Base (Position (..))
import Data.Morpheus.Types.Internal.AST.Name (TypeName)
import Data.Morpheus.Types.Internal.AST.Selection
  ( Fragment (..),
    Selection (..),
    SelectionContent (..),
    SelectionSet,
    UnionTag (..),
  )
import Data.Morpheus.Types.Internal.AST.Stage (RAW, VALID)
import Data.Morpheus.Types.Internal.AST.TypeCategory
  ( IMPLEMENTABLE,
    OUT,
    toCategory,
  )
import Data.Morpheus.Types.Internal.AST.TypeSystem
  ( TypeContent (..),
    TypeDefinition (..),
    UnionTypeDefinition,
    mkType,
  )
import Data.Morpheus.Types.Internal.Validation
  ( FragmentValidator,
    Scope (..),
    askInterfaceTypes,
    askTypeMember,
    asksScope,
  )
import Data.Morpheus.Validation.Query.Fragment
  ( ValidateFragmentSelection,
    castFragmentType,
    validateSpread,
  )
import Relude hiding (empty, join)

-- returns all Fragments used for Possible Types
splitFragment ::
  (ValidateFragmentSelection s) =>
  ( Fragment RAW ->
    FragmentValidator s (SelectionSet VALID)
  ) ->
  [TypeDefinition IMPLEMENTABLE VALID] ->
  Selection RAW ->
  FragmentValidator s (Either UnionTag (Selection RAW))
splitFragment :: forall (s :: Stage).
ValidateFragmentSelection s =>
(Fragment RAW -> FragmentValidator s (SelectionSet VALID))
-> [TypeDefinition IMPLEMENTABLE VALID]
-> Selection RAW
-> FragmentValidator s (Either UnionTag (Selection RAW))
splitFragment Fragment RAW -> FragmentValidator s (SelectionSet VALID)
_ [TypeDefinition IMPLEMENTABLE VALID]
_ x :: Selection RAW
x@Selection {} = forall (f :: * -> *) a. Applicative f => a -> f a
pure (forall a b. b -> Either a b
Right Selection RAW
x)
splitFragment Fragment RAW -> FragmentValidator s (SelectionSet VALID)
f [TypeDefinition IMPLEMENTABLE VALID]
types (Spread Directives RAW
_ Ref FragmentName
ref) = forall a b. a -> Either a b
Left forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> forall (s :: Stage).
ValidateFragmentSelection s =>
(Fragment RAW -> FragmentValidator s (SelectionSet VALID))
-> [TypeName] -> Ref FragmentName -> FragmentValidator s UnionTag
validateSpread Fragment RAW -> FragmentValidator s (SelectionSet VALID)
f (forall (a :: TypeCategory) (s :: Stage).
TypeDefinition a s -> TypeName
typeName forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> [TypeDefinition IMPLEMENTABLE VALID]
types) Ref FragmentName
ref
splitFragment Fragment RAW -> FragmentValidator s (SelectionSet VALID)
f [TypeDefinition IMPLEMENTABLE VALID]
types (InlineFragment fragment :: Fragment RAW
fragment@Fragment {TypeName
fragmentType :: forall (stage :: Stage). Fragment stage -> TypeName
fragmentType :: TypeName
fragmentType}) =
  forall a b. a -> Either a b
Left forall b c a. (b -> c) -> (a -> b) -> a -> c
. TypeName -> SelectionSet VALID -> UnionTag
UnionTag TypeName
fragmentType
    forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> ( forall (s :: Stage) (s1 :: Stage).
Maybe FragmentName
-> Position
-> [TypeName]
-> Fragment s
-> FragmentValidator s1 (Fragment s)
castFragmentType forall a. Maybe a
Nothing (forall (stage :: Stage). Fragment stage -> Position
fragmentPosition Fragment RAW
fragment) (forall (a :: TypeCategory) (s :: Stage).
TypeDefinition a s -> TypeName
typeName forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> [TypeDefinition IMPLEMENTABLE VALID]
types) Fragment RAW
fragment
            forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= Fragment RAW -> FragmentValidator s (SelectionSet VALID)
f
        )

exploreFragments ::
  (ValidateFragmentSelection s) =>
  ( Fragment RAW ->
    FragmentValidator s (SelectionSet VALID)
  ) ->
  OrdMap TypeName (TypeDefinition IMPLEMENTABLE VALID) ->
  SelectionSet RAW ->
  FragmentValidator s ([UnionTag], SelectionSet RAW)
exploreFragments :: forall (s :: Stage).
ValidateFragmentSelection s =>
(Fragment RAW -> FragmentValidator s (SelectionSet VALID))
-> OrdMap TypeName (TypeDefinition IMPLEMENTABLE VALID)
-> SelectionSet RAW
-> FragmentValidator s ([UnionTag], SelectionSet RAW)
exploreFragments Fragment RAW -> FragmentValidator s (SelectionSet VALID)
validateFragment OrdMap TypeName (TypeDefinition IMPLEMENTABLE VALID)
types SelectionSet RAW
selectionSet = do
  ([UnionTag]
tags, [Selection RAW]
selections) <- forall a b. [Either a b] -> ([a], [b])
partitionEithers forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> forall (t :: * -> *) (f :: * -> *) a b.
(Traversable t, Applicative f) =>
(a -> f b) -> t a -> f (t b)
traverse (forall (s :: Stage).
ValidateFragmentSelection s =>
(Fragment RAW -> FragmentValidator s (SelectionSet VALID))
-> [TypeDefinition IMPLEMENTABLE VALID]
-> Selection RAW
-> FragmentValidator s (Either UnionTag (Selection RAW))
splitFragment Fragment RAW -> FragmentValidator s (SelectionSet VALID)
validateFragment (forall (t :: * -> *) a. Foldable t => t a -> [a]
toList OrdMap TypeName (TypeDefinition IMPLEMENTABLE VALID)
types)) (forall (t :: * -> *) a. Foldable t => t a -> [a]
toList SelectionSet RAW
selectionSet)
  Position
selectionPosition <- forall a. a -> Maybe a -> a
fromMaybe (Int -> Int -> Position
Position Int
0 Int
0) forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> forall (s :: Stage) ctx (m :: * -> *) a.
MonadReader (ValidatorContext s ctx) m =>
(Scope -> a) -> m a
asksScope Scope -> Maybe Position
position
  ([UnionTag]
tags,)
    forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> forall (m :: * -> *) k a (map :: * -> * -> *).
(Monad m, KeyOf k a, FromList m map k a) =>
[a] -> m (map k a)
fromElems
      ( ( Selection
            { selectionName :: FieldName
selectionName = FieldName
"__typename",
              selectionAlias :: Maybe FieldName
selectionAlias = forall a. Maybe a
Nothing,
              Position
selectionPosition :: Position
selectionPosition :: Position
selectionPosition,
              selectionArguments :: Arguments RAW
selectionArguments = forall coll. Empty coll => coll
empty,
              selectionContent :: SelectionContent RAW
selectionContent = forall (s :: Stage). SelectionContent s
SelectionField,
              selectionDirectives :: Directives RAW
selectionDirectives = forall coll. Empty coll => coll
empty
            }
        )
          forall a. a -> [a] -> [a]
: [Selection RAW]
selections
      )

-- sorts Fragment by conditional Types
-- [
--   ( Type for Tag User , [ Fragment for User] )
--   ( Type for Tag Product , [ Fragment for Product] )
-- ]
tagUnionFragments ::
  [UnionTag] ->
  OrdMap TypeName (TypeDefinition IMPLEMENTABLE VALID) ->
  HashMap TypeName [SelectionSet VALID]
tagUnionFragments :: [UnionTag]
-> OrdMap TypeName (TypeDefinition IMPLEMENTABLE VALID)
-> HashMap TypeName [SelectionSet VALID]
tagUnionFragments [UnionTag]
fragments OrdMap TypeName (TypeDefinition IMPLEMENTABLE VALID)
types = forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap [TypeName] -> [SelectionSet VALID]
categorizeType HashMap TypeName [TypeName]
getSelectedTypes
  where
    getSelectedTypes :: HashMap TypeName [TypeName]
    getSelectedTypes :: HashMap TypeName [TypeName]
getSelectedTypes = forall l. IsList l => [Item l] -> l
fromList (forall a b. (a -> b) -> [a] -> [b]
map UnionTag -> (TypeName, [TypeName])
select [UnionTag]
fragments)
      where
        select :: UnionTag -> (TypeName, [TypeName])
select UnionTag {TypeName
unionTagName :: UnionTag -> TypeName
unionTagName :: TypeName
unionTagName} =
          ( TypeName
unionTagName,
            forall k (c :: * -> *) d a.
IsMap k c =>
d -> (a -> d) -> k -> c a -> d
selectOr
              [TypeName
unionTagName]
              forall (a :: TypeCategory) (s :: Stage).
TypeDefinition a s -> [TypeName]
getCompatibleTypes
              TypeName
unionTagName
              OrdMap TypeName (TypeDefinition IMPLEMENTABLE VALID)
types
          )
    categorizeType ::
      [TypeName] -> [SelectionSet VALID]
    categorizeType :: [TypeName] -> [SelectionSet VALID]
categorizeType [TypeName]
compatibleTypes =
      UnionTag -> SelectionSet VALID
unionTagSelection
        forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> forall a. (a -> Bool) -> [a] -> [a]
filter
          ((forall (f :: * -> *) a.
(Foldable f, DisallowElem f, Eq a) =>
a -> f a -> Bool
`elem` [TypeName]
compatibleTypes) forall b c a. (b -> c) -> (a -> b) -> a -> c
. UnionTag -> TypeName
unionTagName)
          [UnionTag]
fragments

getCompatibleTypes :: TypeDefinition a s -> [TypeName]
getCompatibleTypes :: forall (a :: TypeCategory) (s :: Stage).
TypeDefinition a s -> [TypeName]
getCompatibleTypes TypeDefinition {TypeName
typeName :: TypeName
typeName :: forall (a :: TypeCategory) (s :: Stage).
TypeDefinition a s -> TypeName
typeName, typeContent :: forall (a :: TypeCategory) (s :: Stage).
TypeDefinition a s -> TypeContent 'True a s
typeContent = DataObject {[TypeName]
objectImplements :: forall (s :: Stage) (a :: TypeCategory).
CondTypeContent OBJECT a s -> [TypeName]
objectImplements :: [TypeName]
objectImplements}} = TypeName
typeName forall a. a -> [a] -> [a]
: [TypeName]
objectImplements
getCompatibleTypes TypeDefinition {TypeName
typeName :: TypeName
typeName :: forall (a :: TypeCategory) (s :: Stage).
TypeDefinition a s -> TypeName
typeName} = [TypeName
typeName]

joinClusters ::
  SelectionSet VALID ->
  HashMap TypeName [SelectionSet VALID] ->
  FragmentValidator s (SelectionContent VALID)
joinClusters :: forall (s :: Stage).
SelectionSet VALID
-> HashMap TypeName [SelectionSet VALID]
-> FragmentValidator s (SelectionContent VALID)
joinClusters SelectionSet VALID
selSet HashMap TypeName [SelectionSet VALID]
typedSelections
  | forall (t :: * -> *) a. Foldable t => t a -> Bool
null HashMap TypeName [SelectionSet VALID]
typedSelections = forall (f :: * -> *) a. Applicative f => a -> f a
pure (forall (s :: Stage). SelectionSet s -> SelectionContent s
SelectionSet SelectionSet VALID
selSet)
  | Bool
otherwise =
      forall (t :: * -> *) (f :: * -> *) a b.
(Traversable t, Applicative f) =>
(a -> f b) -> t a -> f (t b)
traverse forall (s :: Stage).
(TypeName, [SelectionSet VALID]) -> FragmentValidator s UnionTag
mkUnionTag (forall k v. HashMap k v -> [(k, v)]
HM.toList HashMap TypeName [SelectionSet VALID]
typedSelections)
        forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap (SelectionSet VALID
-> UnionSelection VALID -> SelectionContent VALID
UnionSelection SelectionSet VALID
selSet) forall b c a. (b -> c) -> (a -> b) -> a -> c
. forall (m :: * -> *) a. HistoryT m a -> m a
startHistory forall b c a. (b -> c) -> (a -> b) -> a -> c
. forall (m :: * -> *) k a (map :: * -> * -> *).
(Monad m, KeyOf k a, FromList m map k a) =>
[a] -> m (map k a)
fromElems
  where
    mkUnionTag :: (TypeName, [SelectionSet VALID]) -> FragmentValidator s UnionTag
    mkUnionTag :: forall (s :: Stage).
(TypeName, [SelectionSet VALID]) -> FragmentValidator s UnionTag
mkUnionTag (TypeName
typeName, [SelectionSet VALID]
fragments) = TypeName -> SelectionSet VALID -> UnionTag
UnionTag TypeName
typeName forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> forall (m :: * -> *) a. HistoryT m a -> m a
startHistory (forall (m :: * -> *) a e.
(Monad m, Merge m a, MonadError e m) =>
NonEmpty a -> m a
mergeConcat (SelectionSet VALID
selSet forall a. a -> [a] -> NonEmpty a
:| [SelectionSet VALID]
fragments))

validateInterfaceSelection ::
  ValidateFragmentSelection s =>
  (Fragment RAW -> FragmentValidator s (SelectionSet VALID)) ->
  (TypeDefinition IMPLEMENTABLE VALID -> SelectionSet RAW -> FragmentValidator s (SelectionSet VALID)) ->
  TypeDefinition IMPLEMENTABLE VALID ->
  SelectionSet RAW ->
  FragmentValidator s (SelectionContent VALID)
validateInterfaceSelection :: forall (s :: Stage).
ValidateFragmentSelection s =>
(Fragment RAW -> FragmentValidator s (SelectionSet VALID))
-> (TypeDefinition IMPLEMENTABLE VALID
    -> SelectionSet RAW -> FragmentValidator s (SelectionSet VALID))
-> TypeDefinition IMPLEMENTABLE VALID
-> SelectionSet RAW
-> FragmentValidator s (SelectionContent VALID)
validateInterfaceSelection
  Fragment RAW -> FragmentValidator s (SelectionSet VALID)
validateFragment
  TypeDefinition IMPLEMENTABLE VALID
-> SelectionSet RAW -> FragmentValidator s (SelectionSet VALID)
validate
  typeDef :: TypeDefinition IMPLEMENTABLE VALID
typeDef@TypeDefinition {TypeName
typeName :: TypeName
typeName :: forall (a :: TypeCategory) (s :: Stage).
TypeDefinition a s -> TypeName
typeName}
  SelectionSet RAW
inputSelectionSet = do
    OrdMap TypeName (TypeDefinition IMPLEMENTABLE VALID)
possibleTypes <- forall (m :: * -> *) (s :: Stage) ctx.
(MonadError GQLError m, MonadReader (ValidatorContext s ctx) m,
 FromCategory (TypeContent 'True) ANY IMPLEMENTABLE) =>
TypeDefinition IMPLEMENTABLE s
-> m (OrdMap TypeName (TypeDefinition IMPLEMENTABLE s))
askInterfaceTypes TypeDefinition IMPLEMENTABLE VALID
typeDef
    ([UnionTag]
spreads, MergeMap 'True FieldName (Selection RAW)
selectionSet) <- forall (s :: Stage).
ValidateFragmentSelection s =>
(Fragment RAW -> FragmentValidator s (SelectionSet VALID))
-> OrdMap TypeName (TypeDefinition IMPLEMENTABLE VALID)
-> SelectionSet RAW
-> FragmentValidator s ([UnionTag], SelectionSet RAW)
exploreFragments Fragment RAW -> FragmentValidator s (SelectionSet VALID)
validateFragment OrdMap TypeName (TypeDefinition IMPLEMENTABLE VALID)
possibleTypes SelectionSet RAW
inputSelectionSet
    MergeMap 'False FieldName (Selection VALID)
validSelectionSet <- TypeDefinition IMPLEMENTABLE VALID
-> SelectionSet RAW -> FragmentValidator s (SelectionSet VALID)
validate TypeDefinition IMPLEMENTABLE VALID
typeDef MergeMap 'True FieldName (Selection RAW)
selectionSet
    let tags :: HashMap TypeName [SelectionSet VALID]
tags = [UnionTag]
-> OrdMap TypeName (TypeDefinition IMPLEMENTABLE VALID)
-> HashMap TypeName [SelectionSet VALID]
tagUnionFragments [UnionTag]
spreads OrdMap TypeName (TypeDefinition IMPLEMENTABLE VALID)
possibleTypes
    let interfaces :: [MergeMap 'False FieldName (Selection VALID)]
interfaces = forall k (c :: * -> *) d a.
IsMap k c =>
d -> (a -> d) -> k -> c a -> d
selectOr [] forall a. a -> a
id TypeName
typeName HashMap TypeName [SelectionSet VALID]
tags
    MergeMap 'False FieldName (Selection VALID)
defaultSelection <- forall (m :: * -> *) a. HistoryT m a -> m a
startHistory forall a b. (a -> b) -> a -> b
$ forall (m :: * -> *) a e.
(Monad m, Merge m a, MonadError e m) =>
NonEmpty a -> m a
mergeConcat (MergeMap 'False FieldName (Selection VALID)
validSelectionSet forall a. a -> [a] -> NonEmpty a
:| [MergeMap 'False FieldName (Selection VALID)]
interfaces)
    forall (s :: Stage).
SelectionSet VALID
-> HashMap TypeName [SelectionSet VALID]
-> FragmentValidator s (SelectionContent VALID)
joinClusters MergeMap 'False FieldName (Selection VALID)
defaultSelection (forall k v. (Eq k, Hashable k) => k -> HashMap k v -> HashMap k v
HM.delete TypeName
typeName HashMap TypeName [SelectionSet VALID]
tags)

mkUnionRootType :: FragmentValidator s (TypeDefinition IMPLEMENTABLE VALID)
mkUnionRootType :: forall (s :: Stage).
FragmentValidator s (TypeDefinition IMPLEMENTABLE VALID)
mkUnionRootType = (forall (a :: TypeCategory) (s :: Stage).
TypeName -> TypeContent 'True a s -> TypeDefinition a s
`mkType` forall (s :: Stage) (a :: TypeCategory).
[TypeName]
-> FieldsDefinition OUT s -> TypeContent (OBJECT <=? a) a s
DataObject [] forall coll. Empty coll => coll
empty) forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> forall (s :: Stage) ctx (m :: * -> *) a.
MonadReader (ValidatorContext s ctx) m =>
(Scope -> a) -> m a
asksScope Scope -> TypeName
currentTypeName

validateUnionSelection ::
  ValidateFragmentSelection s =>
  (Fragment RAW -> FragmentValidator s (SelectionSet VALID)) ->
  (TypeDefinition IMPLEMENTABLE VALID -> SelectionSet RAW -> FragmentValidator s (SelectionSet VALID)) ->
  UnionTypeDefinition OUT VALID ->
  SelectionSet RAW ->
  FragmentValidator s (SelectionContent VALID)
validateUnionSelection :: forall (s :: Stage).
ValidateFragmentSelection s =>
(Fragment RAW -> FragmentValidator s (SelectionSet VALID))
-> (TypeDefinition IMPLEMENTABLE VALID
    -> SelectionSet RAW -> FragmentValidator s (SelectionSet VALID))
-> UnionTypeDefinition OUT VALID
-> SelectionSet RAW
-> FragmentValidator s (SelectionContent VALID)
validateUnionSelection Fragment RAW -> FragmentValidator s (SelectionSet VALID)
validateFragment TypeDefinition IMPLEMENTABLE VALID
-> SelectionSet RAW -> FragmentValidator s (SelectionSet VALID)
validate UnionTypeDefinition OUT VALID
members SelectionSet RAW
selectionSet = do
  OrdMap TypeName (TypeDefinition IMPLEMENTABLE VALID)
unionTypes <- forall (t :: * -> *) (f :: * -> *) a b.
(Traversable t, Applicative f) =>
(a -> f b) -> t a -> f (t b)
traverse (forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap forall (a :: TypeCategory -> Stage -> *) (k :: TypeCategory)
       (k' :: TypeCategory) (s :: Stage).
ToCategory a k k' =>
a k s -> a k' s
toCategory forall b c a. (b -> c) -> (a -> b) -> a -> c
. forall (m :: * -> *) c (cat :: TypeCategory) (s :: Stage) ctx.
Constraints m c cat s ctx =>
UnionMember cat s -> m (TypeDefinition (ToOBJECT cat) s)
askTypeMember) UnionTypeDefinition OUT VALID
members
  ([UnionTag]
spreads, MergeMap 'True FieldName (Selection RAW)
selSet) <- forall (s :: Stage).
ValidateFragmentSelection s =>
(Fragment RAW -> FragmentValidator s (SelectionSet VALID))
-> OrdMap TypeName (TypeDefinition IMPLEMENTABLE VALID)
-> SelectionSet RAW
-> FragmentValidator s ([UnionTag], SelectionSet RAW)
exploreFragments Fragment RAW -> FragmentValidator s (SelectionSet VALID)
validateFragment OrdMap TypeName (TypeDefinition IMPLEMENTABLE VALID)
unionTypes SelectionSet RAW
selectionSet
  TypeDefinition IMPLEMENTABLE VALID
typeDef <- forall (s :: Stage).
FragmentValidator s (TypeDefinition IMPLEMENTABLE VALID)
mkUnionRootType
  MergeMap 'False FieldName (Selection VALID)
validSelection <- TypeDefinition IMPLEMENTABLE VALID
-> SelectionSet RAW -> FragmentValidator s (SelectionSet VALID)
validate TypeDefinition IMPLEMENTABLE VALID
typeDef MergeMap 'True FieldName (Selection RAW)
selSet
  forall (s :: Stage).
SelectionSet VALID
-> HashMap TypeName [SelectionSet VALID]
-> FragmentValidator s (SelectionContent VALID)
joinClusters MergeMap 'False FieldName (Selection VALID)
validSelection ([UnionTag]
-> OrdMap TypeName (TypeDefinition IMPLEMENTABLE VALID)
-> HashMap TypeName [SelectionSet VALID]
tagUnionFragments [UnionTag]
spreads OrdMap TypeName (TypeDefinition IMPLEMENTABLE VALID)
unionTypes)