import * as Notifications from 'expo-notifications'
import {router} from 'expo-router'
import {useEffect} from 'react'

import {getActiveConversationId} from '@/stores/dms'

type DmPayload = {type: 'dm'; conversationId: string}

const isDmPayload = (data: unknown): data is DmPayload =>
  typeof data === 'object' &&
  data !== null &&
  'type' in data &&
  data.type === 'dm' &&
  'conversationId' in data &&
  typeof data.conversationId === 'string'

// foreground behavior: show banners, except for the conversation the
// user is already looking at
Notifications.setNotificationHandler({
  handleNotification: (notification) => {
    const data = notification.request.content.data
    const suppress =
      isDmPayload(data) &&
      data.conversationId === getActiveConversationId()
    return Promise.resolve({
      shouldShowBanner: !suppress,
      shouldShowList: !suppress,
      shouldPlaySound: false,
      shouldSetBadge: false,
    })
  },
})

const openFromNotification = (data: unknown): void => {
  if (isDmPayload(data)) router.push(`/dms/${data.conversationId}`)
}

// deep-link notification taps, including the tap that cold-started the app
export const useNotificationObserver = (): void => {
  useEffect(() => {
    const sub = Notifications.addNotificationResponseReceivedListener(
      (response) =>
        openFromNotification(
          response.notification.request.content.data,
        ),
    )
    void Notifications.getLastNotificationResponseAsync().then(
      (response) => {
        if (response)
          openFromNotification(
            response.notification.request.content.data,
          )
      },
    )
    return () => sub.remove()
  }, [])
}
