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

export const useStatementdetailStore = defineStore('statementdetail', {
  state: () => ({
    details: [],
    loading: false,
    error: null
  }),

  actions: {
    async loadDetails ({ accountCode, startDate, endDate, parislemler }) {
      if (!accountCode) {
        this.error = 'Geçerli bir cari kod seçilmedi.'
        return
      }

      this.loading = true
      this.error = null

      try {
        // ✅ Params (arrayFormat=repeat global)
        const params = {
          startdate: startDate,
          enddate: endDate
        }

        if (Array.isArray(parislemler) && parislemler.length > 0) {
          params.parislemler = parislemler.filter(
            p => p !== undefined && p !== null && p !== ''
          )
        }

        // 🔐 TOKEN + SERIALIZER + ERROR HANDLING OTOMATİK
        const res = await api.get(
          `/statements/${accountCode}/details`,
          { params }
        )

        this.details = res.data || []

      } catch (err) {
        console.error('❌ Details yüklenemedi:', err)
        this.error =
          err?.data?.message ||
          err?.message ||
          'Detaylar yüklenemedi'
      } finally {
        this.loading = false
      }
    },

    getDetailsByBelge (belgeNo) {
      return this.details.filter(
        d => d.belge_ref_numarasi === belgeNo
      )
    },

    reset () {
      this.details = []
      this.loading = false
      this.error = null
    }
  }
})
