
module Gargantext.API.Server.Named.Viz (
  graphAPI
  ) where

import Control.Lens (view)
import Gargantext.API.Admin.Auth (withNamedAccess)
import Gargantext.API.Admin.Auth.Types (AuthenticatedUser, PathId(..))
import Gargantext.API.Admin.EnvTypes (Env)
import Gargantext.API.Errors.Types ( BackendInternalError )
import Gargantext.API.Prelude (GargM)
import Gargantext.API.Routes.Named.Viz qualified as Named
import Gargantext.Core.Config (hasConfig)
import Gargantext.Core.NodeStory.Types (hasNodeStory)
import Gargantext.Core.Viz.Graph.API
import Gargantext.Database.Admin.Types.Node (NodeId, UserId)
import Gargantext.Database.Prelude
import Gargantext.Prelude
import Servant.Server.Generic (AsServerT)


graphAPI :: AuthenticatedUser -> UserId -> NodeId -> Named.GraphAPI (AsServerT (GargM Env BackendInternalError))
graphAPI authenticatedUser userId n = withNamedAccess authenticatedUser (PathNode n) $ Named.GraphAPI
  { getGraphEp          = getGraph n
  , getGraphAsyncEp     = graphAsync n
  , cloneGraphEp        = \grAPI -> do
      cfg <- view hasConfig
      runDBTx $ graphClone cfg userId n grAPI
  , gexfEp              = getGraphGexf      n
  , graphVersionsAPI    = graphVersionsAPI  userId n
  , updateGraphLegendEp = runDBTx . updateGraphLegend n
  }


graphVersionsAPI :: UserId -> NodeId -> Named.GraphVersionsAPI (AsServerT (GargM Env BackendInternalError))
graphVersionsAPI u n = Named.GraphVersionsAPI
  { getGraphVersionsEp      = do
    env <- view hasNodeStory
    runDBTx $ graphVersions env u n
  , recomputeGraphVersionEp = recomputeVersions n
  }
