/** Pinia store for coupon management */
import { defineStore } from 'pinia'
import { ref } from 'vue'
import type { Coupon } from '@/types'
import { couponsService, type CouponFilters } from '@/services/couponsService'

export const useCouponStore = defineStore('coupon', () => {
    const coupons = ref<Coupon[]>([])
    const isLoading = ref(false)
    const error = ref<string | null>(null)
    const myCoupons = ref<any[]>([])
    const filters = ref<CouponFilters>({})

    async function loadCoupons(newFilters?: CouponFilters, isBackground = false) {
        if (isLoading.value && !isBackground) return;
        if (!isBackground) isLoading.value = true
        error.value = null
        if (newFilters) {
            filters.value = newFilters
        }
        try {
            coupons.value = await couponsService.getAllCoupons(filters.value)
        } catch (e) {
            error.value = e instanceof Error ? e.message : 'Failed to load coupons'
            console.error('Error loading coupons:', e)
        } finally {
            if (!isBackground) isLoading.value = false
        }
    }

    async function loadMyCoupons() {
        try {
            myCoupons.value = await couponsService.getMyCoupons()
        } catch (e) {
            console.error('Error loading my coupons:', e)
        }
    }

    async function claimCoupon(id: string) {
        try {
            await couponsService.claimCoupon(id)
            await loadMyCoupons()
            return true
        } catch (e: any) {
            const msg = e.response?.data?.detail || e.message
            throw new Error(msg)
        }
    }

    function setFilters(newFilters: CouponFilters) {
        filters.value = newFilters
        loadCoupons()
    }

    return {
        coupons,
        myCoupons,
        isLoading,
        error,
        filters,
        loadCoupons,
        loadMyCoupons,
        claimCoupon,
        setFilters,
    }
}, {
    persist: {
        pick: ['coupons', 'filters']
    }
})
