import { defineStore } from 'pinia'
import api, { download, extractApiErrorDetail } from 'src/services/api'

export const useDownloadstpdfStore = defineStore('downloadstpdf', {
  actions: {
    async downloadPDF(accountCode, startDate, endDate, parislemler = [], langcode = 'TR', rows = []) {
      try {
        let pdfBlob

        if (Array.isArray(rows) && rows.length > 0) {
          const response = await api.request({
            method: 'POST',
            url: '/export-pdf',
            data: {
              account_code: accountCode,
              start_date: startDate,
              end_date: endDate,
              lang_code: langcode || 'TR',
              rows
            },
            responseType: 'blob',
            timeout: 180000
          })
          pdfBlob = response.data
        } else {
          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 !== ''
            )
          }

          pdfBlob = await download('/export-pdf', params)
        }

        const pdfUrl = window.URL.createObjectURL(
          new Blob([pdfBlob], { type: 'application/pdf' })
        )

        window.open(pdfUrl, '_blank')

        return { ok: true, message: 'PDF hazirlandi' }
      } catch (err) {
        const detail = await extractApiErrorDetail(err)
        const status = err?.status || err?.response?.status || '-'
        console.error(`PDF acma hatasi [${status}] /export-pdf: ${detail}`)

        return {
          ok: false,
          message: detail || 'PDF alinamadi'
        }
      }
    }
  }
})
