import { ref } from 'vue';
import { useUserPreferencesStore } from '../../domain/setting/application/store/userPreferencesStore';

const notifications = ref([]);
let nextId = 1;

export function useNotifications() {
    const addNotification = (message, type = 'info', duration = 4000) => {
        const notification = {
            id: nextId++,
            message,
            type, // 'success', 'error', 'warning', 'info'
            duration,
            timestamp: Date.now()
        };

        notifications.value.push(notification);

        // Auto-remove après la durée spécifiée
        if (duration > 0) {
            setTimeout(() => {
                removeNotification(notification.id);
            }, duration);
        }

        return notification.id;
    };

    const removeNotification = (id) => {
        const index = notifications.value.findIndex(n => n.id === id);
        if (index > -1) {
            notifications.value.splice(index, 1);
        }
    };

    const clearAll = () => {
        notifications.value = [];
    };

    const showSuccess = (message, duration) => {
        const prefs = useUserPreferencesStore();
        return addNotification(message, 'success', duration ?? prefs.toastDuration);
    };

    const showError = (message, duration) => {
        const prefs = useUserPreferencesStore();
        return addNotification(message, 'error', duration ?? prefs.toastDuration);
    };

    const showWarning = (message, duration) => {
        const prefs = useUserPreferencesStore();
        return addNotification(message, 'warning', duration ?? prefs.toastDuration);
    };

    const showInfo = (message, duration) => {
        const prefs = useUserPreferencesStore();
        return addNotification(message, 'info', duration ?? prefs.toastDuration);
    };

    return {
        notifications,
        addNotification,
        removeNotification,
        clearAll,
        showSuccess,
        showError,
        showWarning,
        showInfo
    };
}
