import { ref, computed } from 'vue';
import axios from 'axios';
import { useUserStore } from '../stores/user';

/**
 * Composable for managing current user's notes
 * 
 * Backend endpoints:
 * - GET /user/note/content - Get current user's notes
 * - GET /user/note/dismiss - Clear (delete) current user's notes
 */
export function useUserNotes() {
    const userStore = useUserStore();
    const notes = computed(() => userStore.notes);
    const loading = ref(false);
    const error = ref(null);

    /**
     * Fetch the current user's notes from the backend
     */
    const fetchNotes = async () => {
        if (!axios) return;
        // Guard: only fetch if the user is authenticated
        if (!userStore.isLoggedIn) return;

        loading.value = true;
        error.value = null;

        try {
            const response = await axios.get('/user/note/content', {
                headers: { 'X-Requested-With': 'XMLHttpRequest' }
            });
            
            // Validate response data - if it's HTML, we likely got redirected to login
            const data = response.data;
            if (typeof data === 'string' && (data.trim().startsWith('<html') || data.trim().startsWith('<!DOCTYPE'))) {
                console.warn('Received HTML response for user notes, ignoring (session likely expired).');
                // If it's HTML, we definitely don't want to display it as a note
                userStore.setNotes(''); 
                return;
            }

            if (data !== null && data !== false && data !== '') {
                userStore.setNotes(data);
            } else {
                userStore.setNotes('');
            }
        } catch (err) {
            console.error('Error fetching user notes:', err);
            error.value = 'Failed to load notes.';
            userStore.setNotes('');
        } finally {
            loading.value = false;
        }
    };

    /**
     * Clear/dismiss the current user's notes
     */
    const dismissNotes = async () => {
        if (!axios) return;
        
        try {
            const response = await axios.get('/user/note/dismiss', {
                headers: { 'X-Requested-With': 'XMLHttpRequest' }
            });
            
            // Validate response - if it's HTML, the session is likely gone
            const data = response.data;
            if (typeof data === 'string' && (data.trim().startsWith('<html') || data.trim().startsWith('<!DOCTYPE'))) {
                console.warn('Received HTML response for dismiss notes, clearing local notes anyway.');
                // Clear local since we know something is wrong with the session
                userStore.clearNotes();
                return true; // Return true so the UI updates
            }

            if (data === true || (response.status >= 200 && response.status < 300)) {
                userStore.clearNotes();
                error.value = null;
                return true;
            }
            return false;
        } catch (err) {
            console.error('Error dismissing user notes:', err);
            error.value = 'Failed to dismiss notes.';
            // Maybe clear local anyway if it fails?
            userStore.clearNotes();
            return true;
        }
    };

    /**
     * Check if notes exist
     */
    const hasNotes = () => {
        return !!notes.value && notes.value.length > 0;
    };

    /**
     * Get the notes content
     * @returns {string|null} The notes content or null if not loaded
     */
    const getNotesContent = () => {
        return notes.value;
    };

    return {
        notes,
        loading,
        error,
        fetchNotes,
        dismissNotes,
        hasNotes,
        getNotesContent
    };
}