import { defineStore } from 'pinia'
import axios from 'axios'
import type { FooterLink } from '../types/footer-link'

export const useFooterLinksStore = defineStore('footerLinks', {
  state: () => ({
    locale: (localStorage.getItem('lang') || 'de'),
    links: [] as Array<FooterLink>
  }),

  actions: {
    async getLinks(locale: string) {
      await this.setLocale(locale)
      return this.links

    },
    getLinkByLabel(oldLabel: string) {
      return this.links.find((link: FooterLink) => (link.Label as string) == oldLabel)

    },

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

    async fetchLinks() {
      const response = await axios.get(import.meta.env.VITE_STRAPI_URL + '/footer-content-pages?&populate[localizations][fields][0]=Label&populate[page][fields][1]=path&locale=' + this.locale, {
        headers: {
          Authorization: "Bearer " + import.meta.env.VITE_STRAPI_TOKEN,
        },
      })
      this.links = response.data.data
    },
  }
})
