import { ref } from 'vue';
import { getFirestore, doc, getDoc, setDoc } from 'firebase/firestore';
import { AppUser } from '../models/AppUser';
import { useMagentoUser } from '../composables/useGlobalVariables';

// Magento user data from PHP integration
export const magentoUserData = ref(null);
export const magentoUserId = ref(null);
export const appUser = ref(null);

/**
 * Initialize Magento user data from global variable or URL params
 */
export function initializeMagentoUser() {
    const userData = useMagentoUser();
    magentoUserData.value = userData;

    // Update magentoUserId if we got data from Magento
    if (userData.userId) {
        magentoUserId.value = userData.userId;
        console.log('Magento user initialized:', userData);
    } else {
        // Generate a temporary ID for standalone testing
        magentoUserId.value = 'guest_' + Date.now();
        console.warn('No Magento user data found. Using temporary guest ID:', magentoUserId.value);
    }

    return userData;
}

/**
 * Fetch user data from Firebase subscriptions collection by magentoUserId.
 * Sets appUser to an AppUser instance. If not found, creates new user with Magento data.
 */
export async function fetchAppUser() {
    const db = getFirestore();
    const docRef = doc(db, 'subscriptions', magentoUserId.value);
    const docSnap = await getDoc(docRef);

    if (docSnap.exists()) {
        appUser.value = new AppUser(docSnap.data());
    } else {
        // User doesn't exist in Firebase - create with Magento data
        await createUserFromMagentoData();
    }
}

/**
 * Create new user in Firebase subscriptions collection using Magento data
 */
async function createUserFromMagentoData() {
    const db = getFirestore();

    // Get Magento user data (email, phone) or use defaults
    const magentoData = magentoUserData.value || {};

    const newUserData = {
        id: magentoUserId.value,
        email: magentoData.email || '',
        phone: magentoData.phone || '',
        notifyEmail: false,
        notifySms: false,
        notifyWhatsapp: false,
        timestamp: Date.now(), // Current timestamp in milliseconds
        topics: []
    };

    try {
        // Add user to Firebase subscriptions collection
        const docRef = doc(db, 'subscriptions', magentoUserId.value);
        await setDoc(docRef, newUserData);

        // Set as current appUser
        appUser.value = new AppUser(newUserData);

        console.log('New user created from Magento data:', newUserData);
    } catch (error) {
        console.error('Error creating user:', error);
        // Even if creation fails, set a minimal user object to prevent null issues
        appUser.value = new AppUser({
            id: magentoUserId.value,
            email: magentoData.email || '',
            phone: magentoData.phone || '',
            notifyEmail: false,
            notifySms: false,
            notifyWhatsapp: false,
            timestamp: Date.now(),
            topics: []
        });
    }
}
