// src/stores/downloadstHeadStore.js
import { defineStore } from 'pinia'
import { download, extractApiErrorDetail } from 'src/services/api'

export const useDownloadstHeadStore = defineStore('downloadstHead', {
  actions: {
    // 📄 Statement Header PDF indir / aç
    async handlestHeadDownload (
      accountCode,
      startDate,
      endDate,
      parislemler,
      langcode = 'TR'
    ) {
      try {
        // ✅ Params (axios paramsSerializer array=repeat destekliyor)
        const params = {
          accountcode: accountCode,
          startdate: startDate,
          enddate: endDate,
          langcode: langcode || 'TR'
        }

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

        // 🔥 API CALL (TOKEN + BLOB + ERROR HANDLING OTOMATİK)
        const blob = await download(
          '/exportstamentheaderreport-pdf',
          params
        )

        const pdfUrl = window.URL.createObjectURL(blob)
        window.open(pdfUrl, '_blank')

        return { ok: true, message: '📄 PDF hazırlandı' }

      } catch (err) {
        const detail = await extractApiErrorDetail(err)
        const status = err?.status || err?.response?.status || '-'
        console.error(`? PDF a�ma hatas� [${status}] /exportstamentheaderreport-pdf: ${detail}`)
        return {
          ok: false,
          message:
            detail ||
            'PDF a�ma hatas�'
        }
      }
    }
  }
})
