module Model.SignIn
  ( createSignInToken
  , getSignInToken
  , signInTokenToUsed
  ) where

import Data.Text (Text)
import Data.Time.Clock (getCurrentTime)

import Control.Monad.IO.Class (liftIO)

import Database.Persist

import Model.Database
import Model.UUID (generateUUID)

createSignInToken :: Text -> Persist Text
createSignInToken email = do
  now <- liftIO getCurrentTime
  token <- liftIO generateUUID
  _ <- insert $ SignIn token now email False
  return token

getSignInToken :: Text -> Persist (Maybe (Entity SignIn))
getSignInToken token =
  selectFirst [SignInToken ==. token] []

signInTokenToUsed :: SignInId -> Persist ()
signInTokenToUsed tokenId =
  update tokenId [SignInIsUsed =. True]