module IHP.AuthSupport.Lockable where

import IHP.Prelude

lock :: forall user. (?modelContext :: ModelContext, CanUpdate user, UpdateField "lockedAt" user user (Maybe UTCTime) (Maybe UTCTime)) => user -> IO user
lock :: forall user.
(?modelContext::ModelContext, CanUpdate user,
 UpdateField
   "lockedAt" user user (Maybe UTCTime) (Maybe UTCTime)) =>
user -> IO user
lock user
user = do
    now <- IO UTCTime
getCurrentTime
    let currentLockedAt :: Maybe UTCTime = user.lockedAt
    let user' :: user = updateField @"lockedAt" (Just now) user
    updateRecord user'

lockDuration :: NominalDiffTime
lockDuration :: NominalDiffTime
lockDuration = let timeInSecs :: Pico
timeInSecs = Pico
60 Pico -> Pico -> Pico
forall a. Num a => a -> a -> a
* Pico
60 in Pico -> NominalDiffTime
secondsToNominalDiffTime Pico
timeInSecs

isLocked :: forall user. (HasField "lockedAt" user (Maybe UTCTime)) => user -> IO Bool
isLocked :: forall user.
HasField "lockedAt" user (Maybe UTCTime) =>
user -> IO Bool
isLocked user
user = do
    now <- IO UTCTime
getCurrentTime
    pure (isLocked' now user)

isLocked' :: forall user. (HasField "lockedAt" user (Maybe UTCTime)) => UTCTime -> user -> Bool
isLocked' :: forall user.
HasField "lockedAt" user (Maybe UTCTime) =>
UTCTime -> user -> Bool
isLocked' UTCTime
now user
user =
    case user
user.lockedAt of
        Just UTCTime
lockedAt ->
            let diff :: NominalDiffTime
diff = UTCTime -> UTCTime -> NominalDiffTime
diffUTCTime UTCTime
now UTCTime
lockedAt
            in NominalDiffTime
diff NominalDiffTime -> NominalDiffTime -> Bool
forall a. Ord a => a -> a -> Bool
< NominalDiffTime
lockDuration
        Maybe UTCTime
Nothing -> Bool
False