// src/stores/accountStore.js
import { defineStore } from 'pinia'
import api from 'src/services/api'

export const useAccountStore = defineStore('account', {
  state: () => ({
    accountOptions: [],
    loading: false,
    error: null
  }),

  actions: {
    async fetchAccounts () {
      this.loading = true
      this.error = null

      try {
        // 🔐 Token interceptor ile otomatik eklenir
        const { data } = await api.get('/accounts')

        this.accountOptions = (Array.isArray(data) ? data : []).map(acc => ({
          label: `${acc.display_code || ''} ${acc.account_name || ''}`.trim(),
          value: acc.account_code
        }))

      } catch (err) {
        console.error('❌ Error fetching accounts:', err)

        if (err?.response?.status === 401) {
          this.error = 'Cari hesapları görüntüleme yetkiniz yok.'
        } else {
          this.error =
            err?.response?.data?.message ||
            err?.message ||
            'Cari hesaplar yüklenemedi'
        }
      } finally {
        this.loading = false
      }
    }

  }
})
