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

export const useStatementdetailStore = defineStore('statementdetail', {
  state: () => ({
    detailsByRow: {},
    detailsByBelge: {},
    loading: false,
    error: null
  }),

  actions: {
    async loadDetails ({ accountCode, belgeNo, rowKey }) {
      if (!accountCode) {
        this.error = 'Gecerli bir cari kod secilmedi.'
        return
      }

      this.loading = true
      this.error = null

      try {
        const normalizedBelgeNo = String(belgeNo || '').trim()
        const params = { belgeno: normalizedBelgeNo }

        if (this.detailsByBelge[normalizedBelgeNo]) {
          const keyCached = String(rowKey || '').trim()
          if (keyCached) {
            this.detailsByRow[keyCached] = this.detailsByBelge[normalizedBelgeNo]
          }
          return
        }

        const res = await api.get(
          `/statements/${encodeURIComponent(accountCode)}/details`,
          { params }
        )

        const key = String(rowKey || '').trim()
        const rows = Array.isArray(res.data) ? res.data : []
        if (normalizedBelgeNo) {
          this.detailsByBelge[normalizedBelgeNo] = rows
        }
        if (key) {
          this.detailsByRow[key] = rows
        }
      } catch (err) {
        console.error('Details yuklenemedi:', err)
        this.error =
          err?.data?.message ||
          err?.message ||
          'Detaylar yuklenemedi'
      } finally {
        this.loading = false
      }
    },

    hasDetailsByRowKey (rowKey) {
      const key = String(rowKey || '').trim()
      return Array.isArray(this.detailsByRow[key])
    },

    getDetailsByRowKey (rowKey) {
      const key = String(rowKey || '').trim()
      return this.detailsByRow[key] || []
    },

    async preloadForRows ({ accountCode, rows, getRowKey }) {
      const tasks = []

      for (const row of rows || []) {
        const belgeNo = String(row?.belge_no || '').trim()
        if (!belgeNo || belgeNo === 'Baslangic_devir') continue

        const rowKey = String(getRowKey(row) || '').trim()
        if (!rowKey) continue
        if (this.hasDetailsByRowKey(rowKey)) continue

        tasks.push(
          this.loadDetails({ accountCode, belgeNo, rowKey })
        )
      }

      if (tasks.length === 0) return
      await Promise.all(tasks)
    },

    reset () {
      this.detailsByRow = {}
      this.detailsByBelge = {}
      this.loading = false
      this.error = null
    }
  }
})
