import type {TrailPost, TrailViewerRole} from '@crumbs/core/schemas'

import {confirmDestructive, showActionSheet} from '@/lib/dialogs'
import {deleteTrailPost} from '@/stores/trail-posts'

// the long-press affordance on a trail post, shared by the trail detail
// and the see-all posts screen: the owner moderates any post, an author
// deletes their own; the delete queues via the outbox so it never rejects
export const useTrailPostActions = (
  trailId: string,
  viewerRole: TrailViewerRole | undefined,
  userId: string | undefined,
) => {
  const canDeletePost = (post: TrailPost) =>
    viewerRole === 'owner' || post.author.id === userId

  const confirmDeletePost = async (post: TrailPost) => {
    const ok = await confirmDestructive({
      title: 'Delete post?',
      message: 'This post will be removed for everyone.',
      actionLabel: 'Delete',
    })
    if (ok) void deleteTrailPost(trailId, post.id)
  }

  const onPostLongPress = (post: TrailPost) => {
    if (!canDeletePost(post)) return
    showActionSheet([
      {
        label: 'Delete post',
        destructive: true,
        onPress: () => void confirmDeletePost(post),
      },
    ])
  }

  return {onPostLongPress}
}
