import { StateCreator } from 'zustand'
import { v4 as uuidv4 } from 'uuid'
import { CreditCard, CardPayment } from '@/lib/types'

export interface CardsSlice {
    creditCards: CreditCard[]
    cardPayments: CardPayment[]

    addCreditCard: (card: Omit<CreditCard, 'id'>) => void
    updateCreditCard: (id: string, card: Partial<CreditCard>) => void
    deleteCreditCard: (id: string) => void

    addCardPayment: (payment: Omit<CardPayment, 'id'>) => void
    deleteCardPayment: (id: string) => void
}

export const createCardsSlice: StateCreator<CardsSlice> = (set) => ({
    creditCards: [],
    cardPayments: [],

    addCreditCard: (card) =>
        set((state) => ({
            creditCards: [...state.creditCards, { ...card, id: uuidv4() }],
        })),

    updateCreditCard: (id, card) =>
        set((state) => ({
            creditCards: state.creditCards.map((c) =>
                c.id === id ? { ...c, ...card } : c
            ),
        })),

    deleteCreditCard: (id) =>
        set((state) => ({
            creditCards: state.creditCards.filter((c) => c.id !== id),
        })),

    addCardPayment: (payment) =>
        set((state) => ({
            cardPayments: [...state.cardPayments, { ...payment, id: uuidv4() }],
        })),

    deleteCardPayment: (id) =>
        set((state) => ({
            cardPayments: state.cardPayments.filter((p) => p.id !== id),
        })),
})
