module Main where

import           ProjectM36.Client
import           Network.Wai (Request)
import           Network.Wai.Handler.Warp (run)
import           Servant.API
import           Servant (serveWithContext)
import           Zero.Persistence (connectM36)
import           Zero.Crypto (generateSecretKey)
import           Zero.Account.Relations (defineAccountRelation)
import           Zero.Account.Verification.Relations (defineVerificationRelation)
import           Zero.Authentication.Server (authenticationContext)
import           Zero.AuthToken.Relations (defineAuthTokenRelation)
import           Zero.SessionToken.Relations (defineSessionTokenRelation)
import           Zero.KeyFetchToken.Relations (defineKeyFetchTokenRelation)
import           Zero.SRP.Relations (defineSRPRelation)
import           Zero.Exchange.Schema (createExchangeSchema)
import           Zero.API (API, api)
import           Zero.Server (server)

------------------------------------------------------------------------------

app sid conn key =
  serveWithContext api (authenticationContext sid conn) (server sid conn key)

-- | Application entry point
main :: IO ()
main = do
  (sid, conn) <- connectM36
  defineRelations sid conn
  -- FIXME: Persist a key and read in production mode
  key <- generateSecretKey
  run 8080 (app sid conn key)
  close conn

-- | Fixtures
defineRelations sid conn = do
  putStrLn "Defining Account relation ..."
  defineAccountRelation sid conn
  putStrLn "Defining Verification relation ..."
  defineVerificationRelation sid conn
  putStrLn "Defining AuthToken relation ..."
  defineAuthTokenRelation sid conn
  putStrLn "Defining SessionToken relation ..."
  defineSessionTokenRelation sid conn
  putStrLn "Defining KeyFetchToken relation ..."
  defineKeyFetchTokenRelation sid conn
--   defineAccountResetTokenRelation sid conn
  putStrLn "Defining SRP relation ..."
  defineSRPRelation sid conn
  putStrLn "Creating Exchange schema ..."
  createExchangeSchema sid conn

