const COLLECTION = 'counters'

export const useCounter = defineStore('counter', {
  state: () => {
    return {
      recordId: null as string | null,
      count: 0
    }
  },
  actions: {
    /**
     * Subscribes to changes of the count in realtime
     * and calls the method to fetch the current count
     */
    subscribeToChanges() {
      if (useUser().isAuthenticated) {
        const { pb } = usePocketBase()
        pb.collection(COLLECTION).subscribe('*', () => this.fetchCurrentCount())
      }
    },
    /**
     * Unsubscribe from the realtime channel
     * Should be done when the user leaves the page for cleanup
     */
    async unsubscribe() {
      const { pb } = usePocketBase()
      pb.collection(COLLECTION).unsubscribe('*')
    },
    /**
     * Fetches the current count and sets the state
     */
    async fetchCurrentCount() {
      const userId = useUser().userId
      if (!userId) return
      try {
        const { pb } = usePocketBase()
        const record = await pb.collection(COLLECTION).getFirstListItem(`userId="${userId}"`)
        this.count = record.count
        this.recordId = record.id
        return
      } catch (error) {
        console.error(error)
      }
    },
    /**
     * Increments the count by the given amount (positive or negative)
     */
    async increment(amount: number) {
      try {
        const { pb } = usePocketBase()
        if (this.recordId) {
          await pb.collection(COLLECTION).update(this.recordId, {
            count: this.count + amount
          })
        } else {
          const record = await pb.collection(COLLECTION).create({
            userId: useUser().userId,
            count: this.count + amount
          })
          this.recordId = record.id
        }
      } catch (error) {
        console.error(error)
      }
    },
    /**
     * Resets the count to zero
     * Uses a custom PocketBase endpoint for demonstration
     */
    async reset() {
      try {
        const { pb } = usePocketBase()
        await pb.send('/counter/reset', {
          method: 'POST'
        })
      } catch (error) {
        console.error(error)
      }
    }
  }
})
