
module Zero.Mail
  (
    sendVerificationEmail
  , resendVerificationEmail
  -- , sendPasswordResetEmail
  ) where

import qualified Zero.Settings as Settings
import qualified Data.Text as T
import qualified Data.Text.Lazy as TL
import           Zero.Persistence (SessionId, Connection, Text)
import           Network.Mail.Mime
import           Zero.Account.Verification.Internal (VerificationCode, generateVerificationCode)
import           Zero.Account.Verification.Model (insertVerificationCode)
import           Zero.Account.Reset.Internal (ResetCode)
-- import           Zero.Account.Reset.Model (generateResetCode, insertResetCode)

-- | Generates a verify_code and sends a verification email to a user.

sendVerificationEmail :: SessionId -> Connection -> Text -> IO ()
sendVerificationEmail sid conn toEmail = do
  code <- generateVerificationCode
  putStrLn ("Generated verification code : " ++ show code)
  _ <- insertVerificationCode sid conn toEmail code
  renderSendMail $ verificationEmail toEmail code

-- | Re-sends an existing verification code to the user.

resendVerificationEmail :: SessionId -> Connection -> Text -> VerificationCode -> IO ()
resendVerificationEmail sid conn toEmail code = do
  putStrLn ("Re-sending verification code : " ++ show code)
  renderSendMail $ verificationEmail toEmail code

-- | Constructs a verification email.

verificationEmail :: Text -> VerificationCode -> Mail
verificationEmail toEmail code =
  simpleMail' to from subject body
  where
    to = Address Nothing toEmail
    from = Address Nothing Settings.domain
    subject = "Account Verification"
    body =
      "Please click the following link to verify your email address: "
      `TL.append` "http://localhost:8080/account/verify/"
      `TL.append` (TL.pack (T.unpack code))

-- sendPasswordResetEmail sid conn toEmail = do
--   code <- generateResetCode
--   putStrLn ("Generated reset code : " ++ show code)
--   _ <- insertResetCode sid conn toEmail code
--   renderSendMail $ passwordResetEmail toEmail code

-- -- | Constructs a password reset email.

-- -- Add a clause 'If this was not you, ...'

-- passwordResetEmail :: Text -> ResetCode -> Mail
-- passwordResetEmail toEmail code =
--   simpleMail' to from subject body
--   where
--     to = Address Nothing toEmail
--     from = Address Nothing Settings.domain
--     subject = "Account Reset"
--     body =
--       "You have requested an account reset. \n"
--       `TL.append` "Please enter the following code:"
--       `TL.append` (TL.pack (T.unpack code)) `TL.append` "\n"
--       `TL.append` "At the following url: "
--       `TL.append` "http://localhost"

