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

import type { Page } from '../types/page'

export const usePageStore = defineStore('pages', {
  state: () => ({
    locale: (localStorage.getItem('lang') || 'de'),
    pages: [] as Array<Page>
  }),

  actions: {
    getPageByTitle(title: string): Page | undefined {
      return this.pages.find((page) => page.Title === title)
    },
    async setLocale(locale: string) {
      if (this.pages.length == 0 || this.locale != locale) {
        this.locale = locale
        await this.fetchPages()
      }
    },
    async fetchPages() {
      const response = await axios.get(import.meta.env.VITE_STRAPI_URL + '/pages?locale=' + this.locale, {
        headers: {
          Authorization: "Bearer " + import.meta.env.VITE_STRAPI_TOKEN,
        },
      })
      this.pages = response.data.data
    }
  }
})
