module Gargantext.API.Node.Corpus.Subcorpus where

import Data.Validity (Validation(..), ValidationChain(..))
import Gargantext.Prelude
import Gargantext.API.Errors.Types (BackendInternalError(..))
import Gargantext.API.Routes.Named.Corpus (MakeSubcorpusAPI(..), SubcorpusParams(..))
import Gargantext.Core.NodeStory.Types (HasNodeStoryEnv)
import Gargantext.Core.NLP (HasNLPServer)
import Gargantext.Core.Text.Corpus (makeSubcorpusFromQuery)
import Gargantext.Core.Text.Corpus.Query (RawQuery(..), parseQuery)
import Gargantext.Core.Types (UserId)
import Gargantext.Core.Types.Individu (User(..))
import Gargantext.Database.Prelude (IsDBCmd)
import Servant.Server.Generic (AsServerT)


makeSubcorpus :: ( HasNodeStoryEnv env BackendInternalError
                 , HasNLPServer    env
                 , IsDBCmd env BackendInternalError m
                 )
  => UserId
  -> MakeSubcorpusAPI (AsServerT m)
makeSubcorpus user = MakeSubcorpusAPI $ \corpusId params -> do
  let queryText = _subcorpusParams_query params
  case parseQuery (RawQuery queryText) of
    Left msg -> throwError $ InternalValidationError $ Validation [Violated $
                  "Failed to parse the query " <> show queryText <> ": " <> msg]
    Right q  -> do
      subcorpusId <- makeSubcorpusFromQuery
             (UserDBId user)
             corpusId
             q
             (_subcorpusParams_reuseParentList params)
      return subcorpusId
