module Utils.Term
  ( termIsActiveE
  ) where

import Import.NoFoundation
import qualified Database.Esqueleto.Legacy as E
import qualified Database.Esqueleto.Utils as E


termIsActiveE :: E.SqlExpr (E.Value UTCTime) -- ^ @now@
              -> E.SqlExpr (E.Value (Maybe UserId)) -- ^ `maybeAuthId`
              -> E.SqlExpr (E.Value TermId)
              -> E.SqlExpr (E.Value Bool)
termIsActiveE now muid tId = E.exists . E.from $ \termActive -> do
  E.where_ $ termActive E.^. TermActiveTerm E.==. tId
  E.where_ $ E.maybe E.true (\f -> E.just f E.==. muid) (termActive E.^. TermActiveFor)
  E.where_ $ termActive E.^. TermActiveFrom E.<=. now
       E.&&. E.maybe E.true (E.>=. now) (termActive E.^. TermActiveTo)
