import { fetchPayments } from '@/api/paymentApi'
import { defineStore } from 'pinia'
import {
  extractErrorMessage,
  showToast,
} from '../composables/useStoreHelpers'
import { createCacheManager } from '../utils/cacheManager'

const cacheManager = createCacheManager('payments', 5 * 60 * 1000) // 5 minutes

export const usePaymentStore = defineStore('payments', {
  state: () => ({
    payments: [],
    total: 0,
    loading: false,
    error: null,
  }),

  actions: {
    async fetchPaymentsLazy({
      page = 1,
      rows = 10,
      sortField = '',
      sortOrder = 0,
      search = '',
      status = '',
      paymentType = '',
    } = {}) {
      const cacheKey = cacheManager.generateKey({
        page,
        rows,
        sortField,
        sortOrder,
        search,
        status,
        paymentType,
      })

      const cached = cacheManager.load(cacheKey)
      if (cached) {
        this.payments = cached.payments || []
        this.total = cached.total || 0
        return { success: true, fromCache: true }
      }

      this.loading = true
      this.error = null

      try {
        const response = await fetchPayments({
          page,
          per_page: rows,
          sort_by: sortField,
          sort_order: sortOrder === 1 ? 'asc' : 'desc',
          search,
          status: status || undefined,
          payment_type: paymentType || undefined,
        })

        const payload = response.data?.data

        if (payload && Array.isArray(payload.data)) {
          // Laravel paginator
          this.payments = payload.data
          this.total = payload.total || payload.data.length
        } else if (Array.isArray(payload)) {
          this.payments = payload
          this.total = payload.length
        } else {
          this.payments = []
          this.total = 0
        }

        cacheManager.save(cacheKey, {
          payments: this.payments,
          total: this.total,
        })
        cacheManager.clearExpired()

        return { success: true }
      } catch (error) {
        this.error = extractErrorMessage(error)
        this.payments = []
        this.total = 0
        showToast('error', 'Error', this.error)
        throw error
      } finally {
        this.loading = false
      }
    },

    clearCache() {
      cacheManager.clearAll()
    },
  },
})
