
module CLI.Admin (
    adminCLI
  , adminCmd
  ) where

import CLI.Parsers
import CLI.Types
import Data.List.NonEmpty qualified as NE
import Data.Text qualified as T
import Gargantext.API.Admin.EnvTypes
import Gargantext.API.Dev
import Gargantext.API.Errors
import Gargantext.Core.Types
import Gargantext.Database.Action.User.New
import Gargantext.Database.Prelude
import Gargantext.Prelude
import Options.Applicative
import Prelude (String)

adminCLI :: AdminArgs -> IO ()
adminCLI (AdminArgs iniPath settingsPath mails) = do
  withDevEnv iniPath settingsPath $ \env -> do
    x <- runCmdDev env ((newUsers $ NE.map cs (NE.fromList mails)) :: Cmd'' DevEnv BackendInternalError (NonEmpty UserId))
    putStrLn (show x :: Text)

adminCmd :: HasCallStack => Mod CommandFields CLI
adminCmd = command "admin" (info (helper <*> fmap CLISub admin_p) (progDesc "Create users."))

admin_p :: Parser CLICmd
admin_p = fmap CCMD_admin $ AdminArgs
  <$> ini_p <*> settings_p
  <*> ( option (maybeReader emails_p) ( long "emails"
                      <> metavar "email1,email2,..."
                      <> help "A comma-separated list of emails."
                      ) )

emails_p :: String -> Maybe [String]
emails_p s = case T.splitOn "," (T.pack s) of
  [] -> Nothing
  xs -> pure $ map T.unpack xs
