{-|
Module      : Gargantext.Database.Action.Query.Node.User
Description : User Node in Gargantext
Copyright   : (c) CNRS, 2017-Present
License     : AGPL + CECILL v3
Maintainer  : team@gargantext.org
Stability   : experimental
Portability : POSIX

-}

module Gargantext.Database.Query.Table.Node.User
  ( getNodeUser
  , getUserByName
  )
  where

import Data.Text qualified as T
import Gargantext.Database.Admin.Types.Hyperdata.User ( HyperdataUser(..) )
import Gargantext.Database.Admin.Types.Node (Node, NodeId(..), pgNodeId)
import Gargantext.Database.Prelude
import Gargantext.Database.Query.Table.Node ( selectNode )
import Gargantext.Prelude
import Opaleye (limit)
import Gargantext.Database.Schema.Node (queryNodeTable, node_name)
import Opaleye.Operators
import Opaleye.SqlTypes
import Gargantext.Database.Query.Table.Node.Error


getNodeUser :: HasNodeError err => NodeId -> DBQuery err x (Node HyperdataUser)
getNodeUser nId = do
  xs <- mkOpaQuery (limit 1 $ selectNode (pgNodeId nId))
  case xs of
    [c] -> pure c
    _   -> dbFailWith $ "Node does not exist: " <> (show nId)

getUserByName :: HasNodeError err => T.Text -> DBQuery err x (Node HyperdataUser)
getUserByName username = do
  result <- mkOpaQuery $ do
    n <- queryNodeTable
    where_ $ (n ^. node_name .== sqlStrictText username)
    pure n
  case result of
    [n]  -> pure n
    _    -> nodeError $ NodeLookupFailed $ UserNameDoesNotExist username
