import { StateCreator } from 'zustand'
import { v4 as uuidv4 } from 'uuid'
import { Alert } from '@/lib/types'

export interface AlertsSlice {
    alerts: Alert[]

    addAlert: (alert: Omit<Alert, 'id' | 'date'>) => void
    markAlertAsRead: (id: string) => void
    deleteAlert: (id: string) => void
    clearAllAlerts: () => void
}

export const createAlertsSlice: StateCreator<AlertsSlice> = (set) => ({
    alerts: [],

    addAlert: (alert) =>
        set((state) => ({
            alerts: [
                ...state.alerts,
                {
                    ...alert,
                    id: uuidv4(),
                    date: new Date().toISOString(),
                },
            ],
        })),

    markAlertAsRead: (id) =>
        set((state) => ({
            alerts: state.alerts.map((a) =>
                a.id === id ? { ...a, isRead: true } : a
            ),
        })),

    deleteAlert: (id) =>
        set((state) => ({
            alerts: state.alerts.filter((a) => a.id !== id),
        })),

    clearAllAlerts: () =>
        set(() => ({
            alerts: [],
        })),
})
