module Routes.Inbox.Follow where

import Control.Logger.Simple qualified as Log
import DB
import Fedi qualified as Fedi
import Routes.Inbox.Accept
import Web.Twain qualified as Twain

handleInboxFollow
  :: Fedi.UserDetails
  -> DB
  -> Fedi.AnyActivity
  -> Fedi.Follow
  -> Twain.ResponderM Twain.Response
handleInboxFollow details db activity follow = do
  let
    id' = follow.id
    actor = follow.otype.actor
    object = follow.otype.atype.object
  case id' of
    Just id'' -> do
      if object == Fedi.LLink (Fedi.Link $ Fedi.actorUrl details)
        then do
          let
            followerEntry =
              ( FollowerEntry
                  { actorId = fromString actor.unwrap
                  , followId = fromString id''.unwrap
                  }
              )
            operation sendAccept = do
              insertFollower db followerEntry sendAccept
                <* Log.logInfo ("New follower: " <> Fedi.pShow followerEntry)

          liftIO $ acceptRequest details actor activity operation

          pure $ Twain.text ""
        else Twain.next
    Nothing ->
      Twain.next

handleInboxUnfollow
  :: Fedi.UserDetails
  -> DB
  -> Fedi.AnyActivity
  -> Fedi.Follow
  -> Twain.ResponderM Twain.Response
handleInboxUnfollow details db activity follow = do
  let
    id' = follow.id
    actor = follow.otype.actor
    object = follow.otype.atype.object
  case id' of
    Just id'' -> do
      if object == Fedi.LLink (Fedi.Link $ Fedi.actorUrl details)
        then do
          let
            followerEntry =
              ( FollowerEntry
                  { actorId = fromString actor.unwrap
                  , followId = fromString id''.unwrap
                  }
              )
            operation sendAccept = do
              deleteFollower
                db
                followerEntry
                ( \deletedId' -> do
                    let
                      deletedId = Fedi.fromMaybe 0 deletedId'
                    sendAccept deletedId
                      <* Log.logInfo ("Deleted follower: " <> Fedi.pShow deletedId)
                )

          liftIO $ acceptRequest details actor activity operation

          pure $ Twain.text ""
        else Twain.next
    Nothing ->
      Twain.next