{-|
Module      : Gargantext.Core.Worker.Jobs
Description : Worker job definitions
Copyright   : (c) CNRS, 2024
License     : AGPL + CECILL v3
Maintainer  : team@gargantext.org
Stability   : experimental
Portability : POSIX

-}


module Gargantext.Core.Worker.Jobs where


import Async.Worker.Broker.Redis (RedisBroker, BrokerInitParams(RedisBrokerInitParams))
import Async.Worker.Broker.Types (Broker, initBroker)
import Async.Worker qualified as Worker
import Async.Worker.Types qualified as Worker
import Async.Worker.Types (HasWorkerBroker)
import Control.Lens (view)
import Database.Redis qualified as Redis
import Gargantext.Core.Config (gc_worker, HasConfig(..))
import Gargantext.Core.Config.Worker (WorkerSettings(..), WorkerDefinition(..), wdToRedisConnectInfo)
import Gargantext.Core.Worker.Jobs.Types (Job(..))
import Gargantext.Database.Prelude (Cmd')
import Gargantext.Prelude


initializeRedisBroker :: (HasWorkerBroker RedisBroker Job)
                      => Redis.ConnectInfo
                      -> IO (Broker RedisBroker (Worker.Job Job))
initializeRedisBroker connInfo = do
  let initParams = RedisBrokerInitParams connInfo

  initBroker initParams


sendJob :: (HasWorkerBroker RedisBroker Job, HasConfig env)
        => Job
        -> Cmd' env err ()
sendJob job = do
  ws <- view $ hasConfig . gc_worker
  -- TODO Try to guess which worker should get this job
  -- let mWd = findDefinitionByName ws workerName
  let mWd = head $ _wsDefinitions ws
  case mWd of
    Nothing -> panicTrace $ "worker definition not found"
    Just wd -> liftBase $ do
      case wdToRedisConnectInfo wd of
        Nothing -> panicTrace $ "worker definition: could not create redis conn info"
        Just connInfo -> do
          b <- initializeRedisBroker connInfo
          let queueName = _wdQueue wd
          void $ Worker.sendJob' $ Worker.mkDefaultSendJob' b queueName job
