import { defineStore } from 'pinia'
import axios from 'axios'

import type { Timeline } from '../types/timeline'


export const useTimelineStore = defineStore('timelines', {
  state: () => ({
    timelines: [] as Array<Timeline>,
    locale: (localStorage.getItem('lang') || 'de')
  }),
  actions: {
    async getTimelines(locale: string) {
      await this.setLocale(locale)
      return this.timelines

    },

    async setLocale(locale: string) {
      if (this.timelines.length == 0 || this.locale != locale) {
        this.locale = locale
        await this.fetchTimelines()
      }
    },

    async fetchTimelines() {
      const response = await axios.get(import.meta.env.VITE_STRAPI_URL + '/timelines?sort=date&locale=' + this.locale, {
        headers: {
          Authorization: "Bearer " + import.meta.env.VITE_STRAPI_TOKEN,
        },
      })
      this.timelines = response.data.data
    },
  }
})
