import {Alert} from 'react-native'

import {unwrap} from '@/lib/errors'
import {rpc} from '@/lib/rpc'
import {addCrumbToTrail} from '@/stores/trail-crumbs'

// after a save, offer the best-matching trail — one tap, never silent
export const suggestTrailFor = async (
  crumbId: string,
): Promise<void> => {
  try {
    const {suggestion} = await unwrap(
      rpc.trails.suggest.$get({query: {crumbId}}),
    )
    if (!suggestion) return
    Alert.alert(
      'Add to trail?',
      `Add this crumb to ${suggestion.name}?`,
      [
        {text: 'Not now', style: 'cancel'},
        {
          text: 'Add',
          onPress: () => {
            void addCrumbToTrail(suggestion.id, crumbId)
          },
        },
      ],
    )
  } catch {
    // suggestions are best-effort
  }
}
