import { defineStore } from 'pinia'
import { useLocalStorage } from '@vueuse/core'

export const useCommentStore = defineStore('comment', {
  state: () => ({
    comment: useLocalStorage('comment', [])
  }),
  hydrate(state, initialState) {  // as nuxt is in SSR localstorage is not available so we need to hydrate the app with data first
    state.comment = useLocalStorage('comment', [])
  },
  actions: {
    add(newComment) {
      this.comment.push(newComment)
      useLocalStorage('comment', this.comment)
    },
  },
  getters: {
    orderedComment: (state) => {
      return (filmId) => {
        return state.comment.filter(comment => comment.filmId === filmId).sort((a, b) => b.added - a.added)
      }
    }
  }
})