// src/stores/statementheaderStore.js
import { defineStore } from 'pinia'
import api from 'src/services/api'
import qs from 'qs'
import dayjs from 'src/boot/dayjs'

export const useStatementheaderStore = defineStore('statementheader', {
  state: () => ({
    headers: [],     // Ana tablo verileri
    details: {},     // Alt tablolar (belge bazlı)
    loading: false,  // Yükleme durumu
    groupOpen: {}    // Para birimi bazlı aç/kapa durumu
  }),

  getters: {
    // 🔹 Benzersiz para birimleri listesi
    currencies(state) {
      const set = new Set()
      for (const r of state.headers) {
        set.add(r.para_birimi || '—')
      }
      return Array.from(set).sort()
    },

    // 🔹 Her para birimi için toplam borç / alacak / bakiye
    totalsByCurrency(state) {
      const out = {}

      for (const r of state.headers) {
        const k = r.para_birimi || '—'
        if (!out[k]) {
          out[k] = { borc: 0, alacak: 0, bakiye: 0, count: 0 }
        }

        out[k].borc   += Number(r.borc)   || 0
        out[k].alacak += Number(r.alacak) || 0
        out[k].bakiye += Number(r.bakiye) || 0
        out[k].count  += 1
      }

      return out
    },

    // 🔹 QTable için satırlar (group + data)
    groupedRows: (state) => {
      const grouped = {}

      for (const row of state.headers) {
        const k = row.para_birimi || '—'
        if (!grouped[k]) grouped[k] = []
        grouped[k].push(row)
      }

      const output = []

      for (const [currency, rows] of Object.entries(grouped)) {
        if (!rows.length) continue

        // 📅 Tarihe göre sırala
        const sorted = [...rows].sort(
          (a, b) => new Date(a.belge_tarihi) - new Date(b.belge_tarihi)
        )

        const lastRow = sorted.at(-1)
        const lastBalance =
          lastRow && lastRow.bakiye != null
            ? Number(lastRow.bakiye)
            : 0

        // 🔹 Grup satırı
        output.push({
          _type: 'group',
          para_birimi: currency,
          sonBakiye: lastBalance
        })

        // 🔹 Alt satırlar
        if (state.groupOpen[currency] !== false) {
          sorted.forEach(r => {
            output.push({ ...r, _type: 'data' })
          })
        }
      }

      return output
    }
  },

  actions: {
    /* ==========================================================
       🔄 ANA STATEMENT LİSTESİ
       ========================================================== */
    async loadStatements(params = {}) {
      this.loading = true

      try {
        const { data } = await api.get(
          '/statements',
          {
            params,
            paramsSerializer: p =>
              qs.stringify(p, { arrayFormat: 'repeat' })
          }
        )

        this.headers = Array.isArray(data) ? data : []


        // 🔹 Yeni gelen para birimleri default açık
        for (const k of this.currencies) {
          if (!(k in this.groupOpen)) {
            this.groupOpen[k] = true
          }
        }
      } catch (err) {
        console.error('❌ Statements yüklenemedi:', err)
        this.headers = []
      } finally {
        this.loading = false
      }
    },

    /* ==========================================================
       📄 BELGE DETAYLARI
       ========================================================== */
    async loadDetails(belgeNo) {
      if (!belgeNo || this.details[belgeNo]) return

      try {
        const { data } = await api.get(
          `/statements/${belgeNo}/details`
        )

        this.details[belgeNo] = Array.isArray(data) ? data : []


      } catch (err) {
        console.error('❌ Details yüklenemedi:', err)
        this.details[belgeNo] = []
      }
    },

    /* ==========================================================
       🔘 GRUP AÇ / KAPA
       ========================================================== */
    toggleGroup(currency) {
      const key = currency || '—'
      this.groupOpen[key] = !this.groupOpen[key]
    },

    openAllGroups() {
      for (const k of this.currencies) {
        this.groupOpen[k] = true
      }
    },

    closeAllGroups() {
      for (const k of this.currencies) {
        this.groupOpen[k] = false
      }
    }
  }
})
