import * as Device from 'expo-device'
import * as Notifications from 'expo-notifications'

import {unwrap} from '@/lib/errors'
import {rpc} from '@/lib/rpc'

// ask contextually (first reminder / first plan), never at onboarding
export const enablePushReminders = async (): Promise<boolean> => {
  if (!Device.isDevice) return false
  const current = await Notifications.getPermissionsAsync()
  const granted = current.granted
    ? true
    : (await Notifications.requestPermissionsAsync()).granted
  if (!granted) return false

  const {data: token} = await Notifications.getExpoPushTokenAsync()
  await unwrap(
    rpc['push-tokens'].$post({
      json: {
        token,
        platform: 'ios',
        timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,
      },
    }),
  )
  return true
}
