{-# LANGUAGE TypeOperators        #-}
{-# LANGUAGE ScopedTypeVariables  #-}

module Gargantext.API.Node.ShareURL where

import Data.Text
import Gargantext.Prelude
import Gargantext.API.Prelude
import Servant
import Gargantext.Core.Types (NodeType, NodeId, unNodeId)
import Gargantext.Database.Prelude (HasConfig (hasConfig), CmdCommon)
import Control.Lens.Getter (view)
import Gargantext.Prelude.Config (gc_url)
import Gargantext.API.Admin.EnvTypes (Env)
import Gargantext.API.Errors (BackendInternalError)

type API = Summary "Fetch URL for sharing a node"
           :> QueryParam "type" NodeType
           :> QueryParam "id" NodeId
           :> Get '[JSON] Text

api :: ServerT API (GargM Env BackendInternalError)
api = getUrl

getUrl :: (CmdCommon env) =>
              Maybe NodeType -> Maybe NodeId -> GargM env BackendInternalError Text
getUrl nt id = do
-- TODO add check that the node is able to be shared (in a shared folder)
    case nt of
        Nothing -> pure "Invalid node Type"
        Just t ->
            case id of
                Nothing -> pure "Invalid node ID"
                Just i -> do
                    url <- view $ hasConfig . gc_url
                    pure $ url <> "/#/share/" <> show t <> "/" <> show (unNodeId i)
