{-# LANGUAGE BangPatterns        #-}
{-# LANGUAGE ScopedTypeVariables #-}

module Test.API.Setup (
    SpecContext(..)
  , withTestDBAndPort
  , withBackendServerAndProxy
  , testWithApplicationOnPort
  , setupEnvironment
  , createAliceAndBob
  , dbEnvSetup
  , newTestEnv
  ) where

import Control.Concurrent.Async qualified as Async
import Control.Concurrent.MVar
import Control.Exception.Safe
import Control.Lens
import Data.ByteString.Lazy.Char8 qualified as C8L
import Data.Cache qualified as InMemory
import Data.Streaming.Network (bindPortTCP)
import Gargantext.API (makeApp)
import Gargantext.API.Admin.EnvTypes (Env (..), env_dispatcher)
import Gargantext.API.Errors.Types
import Gargantext.API.Prelude
import Gargantext.Core.Config hiding (jwtSettings)
import Gargantext.Core.Config.Types (fc_appPort, jwtSettings)
import Gargantext.Core.Notifications (withNotifications)
import Gargantext.Core.Types.Individu
import Gargantext.Database.Action.Flow
import Gargantext.Database.Action.User.New
import Gargantext.Database.Admin.Config (userMaster)
import Gargantext.Database.Admin.Trigger.Init
import Gargantext.Database.Admin.Types.Hyperdata
import Gargantext.Database.Admin.Types.Node (UserId)
import Gargantext.Database.Prelude
import Gargantext.Database.Query.Table.Node (getOrMkList)
import Gargantext.Database.Query.Tree.Root (MkCorpusUser(..))
import Gargantext.MicroServices.ReverseProxy (microServicesProxyApp)
import Gargantext.Prelude hiding (catches, Handler)
import Gargantext.System.Logging
import Network.HTTP.Client.TLS (newTlsManager)
import Network.HTTP.Types
import Network.Wai (Application, responseLBS)
import Network.Wai qualified as Wai
import Network.Wai.Handler.Warp qualified as Warp
import Network.Wai.Handler.Warp.Internal
import Network.WebSockets qualified as WS
import Prelude hiding (show)
import Servant.Auth.Client ()
import Test.Database.Setup (withTestDB)
import Test.Database.Types
import UnliftIO qualified


-- | The context that each spec will be carrying along. This type is
-- polymorphic so that each test can embellish it with test-specific data.
-- 'SpecContext' is a functor, so you can use 'fmap' to change the 'a'.
data SpecContext a =
  SpecContext {
    _sctx_env   :: !TestEnv
  , _sctx_port  :: !Warp.Port
  , _sctx_app   :: !Application
  , _sctx_data  :: !a
  }

instance Functor SpecContext where
  fmap f (SpecContext e p a d) = SpecContext e p a (f d)


newTestEnv :: TestEnv -> Logger (GargM Env BackendInternalError) -> Warp.Port -> IO Env
newTestEnv testEnv logger port = do
  !manager_env  <- newTlsManager

  let config_env    = test_config testEnv & (gc_frontend_config . fc_appPort) .~ port
  -- dbParam        <- pure $ testEnvToPgConnectionInfo testEnv
  -- !pool          <- newPool dbParam

  let pool = _DBHandle $ test_db testEnv
  -- !nodeStory_env <- fromDBNodeStoryEnv pool

  !_env_jwt_settings <- jwtSettings (_gc_secrets config_env)

  pure $ Env
    { _env_logger    = logger
    -- , _env_pool       = Prelude.error "[Test.API.Setup.Env] pool not needed, but forced somewhere"
    , _env_pool = pool
    -- , _env_nodeStory = nodeStory_env
    -- , _env_nodeStory = Prelude.error "[Test.API.Setup.Env] env nodeStory not needed, but forced somewhere"
    , _env_nodeStory = test_nodeStory testEnv
    , _env_manager   = manager_env
    , _env_config    = config_env
    -- , _env_central_exchange = central_exchange
    , _env_dispatcher = errorTrace "[Test.API.Setup.newTestEnv] dispatcher not needed, but forced somewhere"
    , _env_jwt_settings
    }

-- | Run the gargantext server on a random port, picked by Warp, which allows
-- for concurrent tests to be executed in parallel, if we need to.
-- NOTE: We don't need to change the 'NotificationConfig' at this point, because
-- the 'TestEnv' will already contain the correct values for us to use.
-- (cfg 'setup' in 'Test.Database.Setup').
withTestDBAndPort :: (SpecContext () -> IO ()) -> IO ()
withTestDBAndPort action = withTestDB $ \testEnv -> do
  let cfg = test_config testEnv
  withNotifications cfg $ \dispatcher -> do
    withLoggerIO (log_cfg cfg) $ \ioLogger -> do
      env <- newTestEnv testEnv ioLogger 8080
             <&> env_dispatcher .~ dispatcher
      app <- makeApp env
      let stgs = Warp.defaultSettings { settingsOnExceptionResponse = showDebugExceptions }

      -- An exception can be thrown by the websocket server (when client closes connection)
      -- TODO I don't quite understand why the exception has to be caught here
      -- and not under 'WS.runClient'
      catches (Warp.testWithApplicationSettings stgs (pure app) $ \port ->
                  action (SpecContext testEnv port app ()))
        [ Handler $ \(err :: WS.ConnectionException) ->
            case err of
              WS.CloseRequest _ _ ->
                withLogger (log_cfg cfg) $ \ioLogger' ->
                  logTxt ioLogger' DEBUG "[withTestDBAndPort] CloseRequest caught"
              WS.ConnectionClosed ->
                withLogger (log_cfg cfg) $ \ioLogger' ->
                  logTxt ioLogger' DEBUG "[withTestDBAndPort] ConnectionClosed caught"
              _ -> do
                withLogger (log_cfg cfg) $ \ioLogger' ->
                  logTxt ioLogger' ERROR $ "[withTestDBAndPort] unknown exception: " <> show err
                throw err

        -- re-throw any other exceptions
        , Handler $ \(err :: SomeException) -> throw err ]
  where
    log_cfg cfg = cfg ^. gc_logging

-- | Starts the backend server /and/ the microservices proxy, the former at
-- a random port, the latter at a predictable port.
withBackendServerAndProxy :: (((TestEnv, Warp.Port, Warp.Port)) -> IO ()) -> IO ()
withBackendServerAndProxy action =
  withTestDB $ \testEnv -> do
    gargApp <- withLoggerIO (log_cfg testEnv) $ \ioLogger -> do
                 env <- newTestEnv testEnv ioLogger 8080
                 makeApp env
    proxyCache <- InMemory.newCache Nothing
    proxyApp <- withLoggerIO (log_cfg testEnv) $ \ioLogger -> do
                  env <- newTestEnv testEnv ioLogger 8080
                  pure $ microServicesProxyApp proxyCache env

    Warp.testWithApplication (pure gargApp) $ \serverPort ->
      testWithApplicationOnPort (pure proxyApp) proxyPort $
        action (testEnv, serverPort, proxyPort)
  where
    proxyPort = 8090
    cfg te     = test_config te
    log_cfg te = cfg te ^. gc_logging

setupEnvironment :: TestEnv -> IO ()
setupEnvironment env = runTestMonad env $ do
  cfg <- view hasConfig
  runDBTx $ void $ initFirstTriggers "secret_key"
  void $ new_user $ mkNewUser (userMaster <> "@cnrs.com") (GargPassword "secret_key")
  runDBTx $ do
    (masterUserId, _masterRootId, masterCorpusId)
                <- getOrMkRootWithCorpus cfg MkCorpusUserMaster (Nothing :: Maybe HyperdataCorpus)
    masterListId <- getOrMkList masterCorpusId masterUserId
    -- printDebug "[setupEnvironment] masterListId: " masterListId
    void $ initLastTriggers masterListId

-- | Creates two users, Alice & Bob. Alice shouldn't be able to see
-- Bob's private data and vice-versa.
createAliceAndBob :: TestEnv -> IO [UserId]
createAliceAndBob testEnv = runTestMonad testEnv $ do
  let nur1 = mkNewUser "alice@gargan.text" (GargPassword "alice")
  let nur2 = mkNewUser "bob@gargan.text" (GargPassword "bob")

  aliceId <- new_user nur1
  bobId   <- new_user nur2
  pure [aliceId, bobId]

dbEnvSetup :: SpecContext a -> IO (SpecContext a)
dbEnvSetup ctx = do
  let testEnv = _sctx_env ctx
  setupEnvironment testEnv
  _ <- createAliceAndBob testEnv

  pure ctx
  
-- show the full exceptions during testing, rather than shallowing them under a generic
-- "Something went wrong".
showDebugExceptions :: SomeException -> Wai.Response
showDebugExceptions e =
   responseLBS status500 [(hContentType, "text/plain; charset=utf-8")] (C8L.pack $ show e)

-- | A version of 'withApplication' that allows supplying a user-specified port
-- so that we are sure that our garg apps will run on the same port as specified
-- in the 'Env' settings.
testWithApplicationOnPort :: IO Application -> Warp.Port -> IO a -> IO a
testWithApplicationOnPort mkApp userPort action = do
    app <- mkApp
    started <- mkWaiter
    let appSettings =
            Warp.defaultSettings
                { settingsBeforeMainLoop =
                    notify started () >> settingsBeforeMainLoop Warp.defaultSettings
                , settingsPort = userPort
                , settingsOnExceptionResponse = showDebugExceptions
                }
    sock <- bindPortTCP userPort "127.0.0.1"
    result <-
        Async.race
            (Warp.runSettingsSocket appSettings sock app)
            (waitFor started >> action)
    case result of
        Left () -> UnliftIO.throwString "Unexpected: runSettingsSocket exited"
        Right x -> return x

data Waiter a = Waiter
    { notify :: a -> IO ()
    , waitFor :: IO a
    }

mkWaiter :: IO (Waiter a)
mkWaiter = do
    mvar <- newEmptyMVar
    return
        Waiter
            { notify = putMVar mvar
            , waitFor = readMVar mvar
            }
