{-# LANGUAGE OverloadedStrings #-}

import Web.Scotty

import Network.Wai.Middleware.Static
import Network.HTTP.Types.Status (ok200)

import Control.Concurrent (forkIO)

import MonthlyPaymentJob (monthlyPaymentJobListener)

import Data.Text (Text)
import qualified Data.Text.IO as T
import Data.Time.Clock.POSIX (posixSecondsToUTCTime)

import Controller.Index
import Controller.SignIn
import Controller.Payment
import Controller.User
import Controller.Income

import Model.Database (runMigrations)
import Model.Frequency

import qualified Conf

main :: IO ()
main = do
  runMigrations
  _ <- forkIO monthlyPaymentJobListener
  confOrError <- Conf.getConf "application.conf"
  case confOrError of
    Left errorMessage ->
      T.putStrLn errorMessage
    Right conf -> do
      scotty (Conf.port conf) $ do
        middleware $
          staticPolicy (noDots >-> addBase "public")

        get "/" $
          ( do
              signInToken <- param "signInToken" :: ActionM Text
              status ok200
              getIndex conf (Just signInToken)
          ) `rescue` (\_ -> do
            status ok200
            getIndex conf Nothing
          )

        post "/signIn" $ do
          email <- param "email" :: ActionM Text
          signIn conf email

        post "/signOut" (signOut conf)

        -- Users

        get "/users"  getUsers

        get "/whoAmI" whoAmI

        -- Incomes

        get "/incomes" getIncomes

        post "/income" $ do
          creation <- param "creation" :: ActionM Int
          amount <- param "amount" :: ActionM Int
          addIncome (posixSecondsToUTCTime $ (fromIntegral creation) / 1000) amount

        delete "/income" $ do
          incomeId <- param "id" :: ActionM Text
          deleteOwnIncome incomeId

        -- Payments

        get "/payments" getPayments

        post "/payment/add" $ do
          name <- param "name" :: ActionM Text
          cost <- param "cost" :: ActionM Text
          frequency <- param "frequency" :: ActionM Frequency
          createPayment name cost frequency

        delete "/payment" $ do
          paymentId <- param "id" :: ActionM Text
          deleteOwnPayment paymentId