import { db } from '../firebase';
import { doc, setDoc, getFirestore, updateDoc } from 'firebase/firestore';

export async function subscribeUser({
  magentoUserId,
  phone,
  email,
  topic,
  notifyWhatsapp,
  notifySms,
  notifyEmail
}) {
  try {
    // Ensure topic is stored as an array
    const topics = Array.isArray(topic) ? topic : [topic];

    // Use magentoUserId as the document ID
    await setDoc(doc(db, 'subscriptions', magentoUserId), {
      magentoUserId,
      phone,
      email,
      topics, // Store as array
      notifyWhatsapp,
      notifySms,
      notifyEmail,
      timestamp: Date.now() // milliseconds since epoch
    });
    return magentoUserId;
  } catch (e) {
    console.error('Error adding subscription:', e);
    throw e;
  }
}
// Dynamically import AppUser only when needed

/**
 * Subscribe or unsubscribe a user to a CPV code.
 * If user exists, toggles CPV in topics array. If not, creates a new AppUser instance.
 * @param {Object} params - { user, cpvCode, email, phone, notifyWhatsapp, notifySms, notifyEmail, onSubscribe }
 * @returns {Promise<Object|void>} - Returns new AppUser if created, otherwise void.
 */
export async function subscribeOrUnsubscribeUser({ user, cpvCode, email, phone, notifyWhatsapp, notifySms, notifyEmail, onSubscribe }) {
  if (user && user.id) {
    const topics = Array.isArray(user.topics) ? user.topics : [];
    const db = getFirestore();
    const userDocRef = doc(db, 'subscriptions', user.id);
    if (topics.includes(cpvCode)) {
      // Unsubscribe: remove cpv from topics
      const newTopics = topics.filter(t => t !== cpvCode);
      await updateDoc(userDocRef, { topics: newTopics });
      if (onSubscribe) onSubscribe({ action: 'unsubscribe', cpvCode });
    } else {
      // Subscribe: add cpv to topics
      const newTopics = [...topics, cpvCode];
      await updateDoc(userDocRef, { topics: newTopics });
      if (onSubscribe) onSubscribe({ action: 'subscribe', cpvCode });
    }
  } else {
    // No user object: create AppUser model for new subscription
    const { AppUser } = await import('../models/AppUser.js');
    const newUser = new AppUser({
      email,
      phone,
      notifyWhatsapp,
      notifySms,
      notifyEmail,
      topics: [cpvCode]
    });
    if (onSubscribe) onSubscribe(newUser);
    return newUser;
  }
}

/**
 * Update notification preferences for a user in the subscriptions collection.
 * @param {string} userId - The user's document ID (magentoUserId)
 * @param {Object} prefs - Preferences to update (notifyEmail, notifySms, notifyWhatsapp)
 * @returns {Promise<void>}
 */
export async function updateNotificationPrefs(userId, prefs) {
  const db = getFirestore();
  const docRef = doc(db, 'subscriptions', userId);
  await updateDoc(docRef, {
    notifyEmail: !!prefs.notifyEmail,
    notifySms: !!prefs.notifySms,
    notifyWhatsapp: !!prefs.notifyWhatsapp
  });
}

/**
 * Update a single notification field for a user in the subscriptions collection.
 * @param {string} userId - The user's document ID (magentoUserId)
 * @param {string} field - The field to update (notifyEmail, notifySms, notifyWhatsapp)
 * @param {boolean} value - The value to set
 * @returns {Promise<void>}
 */
export async function updateNotificationField(userId, field, value) {
  console.log('[updateNotificationField] User :', userId, 'Field:', field, 'Value:', value);
  const db = getFirestore();
  const docRef = doc(db, 'subscriptions', userId); // Changed to 'subscriptions'
  await updateDoc(docRef, {
    [field]: !!value,
    updatedAt: Date.now() // Track when updated
  });
}
