import type { NotificationsRecord } from '~/types/pocketbase.types'

const COLLECTION = 'notifications'

export const useNotifications = defineStore('notifications', {
  state: () => {
    return {
      notifications: [] as NotificationsRecord[]
    }
  },
  actions: {
    /**
     * Subscribes to changes of notifications in realtime
     * and calls the method to refetch them
     */
    subscribeToChanges() {
      if (useUser().isAuthenticated) {
        const { pb } = usePocketBase()
        pb.collection(COLLECTION).subscribe('*', () => this.fetchNotifications())
      }
    },
    /**
     * Unsubscribe from the realtime channel
     * Should be done when the user leaves the page for cleanup
     */
    unsubscribe() {
      const { pb } = usePocketBase()
      pb.collection(COLLECTION).unsubscribe('*')
    },
    /**
     * Fetches the notifications and sets the state
     */
    async fetchNotifications() {
      const userId = useUser().userId
      if (!userId) return
      try {
        const { pb } = usePocketBase()
        const resultList = await pb.collection(COLLECTION).getList(1, 50, {
          filter: `userId="${userId}"`
        })
        this.notifications = resultList.items
      } catch (error) {
        console.error(error)
      }
    },
    /**
     * Marks a notification as read
     */
    async markAsRead(notificationId: string) {
      try {
        const { pb } = usePocketBase()
        await pb.collection(COLLECTION).update(notificationId, {
          isRead: true
        })
      } catch (error) {
        console.error(error)
      }
    },
    /**
     * Adds a new FCM token for the current user for push notifications
     */
    async addFcmToken(token: string) {
      const userId = useUser().userId
      if (!userId) return
      try {
        const { pb } = usePocketBase()
        const result = await pb.collection('fcm_tokens').getList(1, 0, {
          filter: `token = "${token}"`
        })
        if (result.totalItems > 0) {
          // skip if token already exists
          return
        }
        await pb.collection('fcm_tokens').create({
          userId,
          token
        })
      } catch (error) {
        console.error(error)
      }
    }
  }
})
