{-|
Module      : Gargantext.Core.Worker.Broker
Description : Broker utilities
Copyright   : (c) CNRS, 2017-Present
License     : AGPL + CECILL v3
Maintainer  : team@gargantext.org
Stability   : experimental
Portability : POSIX

-}

module Gargantext.Core.Worker.Broker
  ( initBrokerWithDBCreate )
where

import Async.Worker.Broker.PGMQ (BrokerInitParams(PGMQBrokerInitParams))
import Async.Worker.Broker.Types (initBroker)
import Data.Text qualified as T
import Data.Text.Encoding qualified as TE
import Database.PostgreSQL.Simple qualified as PSQL
import Gargantext.Core.Config.Worker (WorkerSettings(..))
import Gargantext.Core.Worker.PGMQTypes (HasWorkerBroker, Broker)
import Gargantext.Database.Prelude (createDBIfNotExists)
import Gargantext.Prelude



-- | Create DB if not exists, then run 'initBroker' (which, in
-- particular, creates the pgmq extension, if needed)
initBrokerWithDBCreate :: HasWorkerBroker
                       => PSQL.ConnectInfo
                       -> WorkerSettings
                       -> IO Broker
initBrokerWithDBCreate pivotDb ws = do
  -- By using gargantext db credentials, we create pgmq db (if needed)
  let psqlDB = TE.decodeUtf8 $ PSQL.postgreSQLConnectionString pivotDb

  let brokerDb = _wsDatabase ws

  -- Using the pivotDb credentials, create ws Db (if this is the same db host/port)
  when (PSQL.connectHost pivotDb == PSQL.connectHost brokerDb &&
          PSQL.connectPort pivotDb == PSQL.connectPort brokerDb) $ do
    createDBIfNotExists psqlDB (T.pack $ PSQL.connectDatabase brokerDb)
  
  initBroker $ PGMQBrokerInitParams brokerDb $ _wsDefaultVisibilityTimeout ws
