/* firebaseData.jsx — Firestore CRUD operations */

// ===== PROPERTIES =====
async function getProperties() {
  const db = await window.getFirebaseDb();
  const { collection, getDocs } = await import('https://www.gstatic.com/firebasejs/12.13.0/firebase-firestore.js');

  try {
    const querySnapshot = await getDocs(collection(db, 'properties'));
    return querySnapshot.docs.map(doc => ({ id: doc.id, ...doc.data() }));
  } catch (error) {
    console.error('Error fetching properties:', error);
    return [];
  }
}

async function getPropertyById(propertyId) {
  const db = await window.getFirebaseDb();
  const { doc, getDoc } = await import('https://www.gstatic.com/firebasejs/12.13.0/firebase-firestore.js');

  try {
    const docSnap = await getDoc(doc(db, 'properties', propertyId));
    return docSnap.exists() ? { id: docSnap.id, ...docSnap.data() } : null;
  } catch (error) {
    console.error('Error fetching property:', error);
    return null;
  }
}

// ===== RESERVATIONS =====
async function createReservation(guestId, propertyId, checkIn, checkOut, status = 'pending') {
  const db = await window.getFirebaseDb();
  const { collection, addDoc, serverTimestamp } = await import('https://www.gstatic.com/firebasejs/12.13.0/firebase-firestore.js');

  try {
    const docRef = await addDoc(collection(db, 'reservations'), {
      guestId,
      propertyId,
      checkIn: new Date(checkIn),
      checkOut: new Date(checkOut),
      status, // pending, confirmed, checked-in, checked-out
      doorCode: Math.random().toString().slice(2, 6),
      wifi: 'NovusGuest-2024',
      createdAt: serverTimestamp(),
    });
    return { id: docRef.id };
  } catch (error) {
    console.error('Error creating reservation:', error);
    throw error;
  }
}

async function getReservationsByGuest(guestId) {
  const db = await window.getFirebaseDb();
  const { collection, query, where, getDocs } = await import('https://www.gstatic.com/firebasejs/12.13.0/firebase-firestore.js');

  try {
    const q = query(collection(db, 'reservations'), where('guestId', '==', guestId));
    const querySnapshot = await getDocs(q);
    return querySnapshot.docs.map(doc => ({ id: doc.id, ...doc.data() }));
  } catch (error) {
    console.error('Error fetching reservations:', error);
    return [];
  }
}

async function getReservationsByProperty(propertyId) {
  const db = await window.getFirebaseDb();
  const { collection, query, where, getDocs } = await import('https://www.gstatic.com/firebasejs/12.13.0/firebase-firestore.js');

  try {
    const q = query(collection(db, 'reservations'), where('propertyId', '==', propertyId));
    const querySnapshot = await getDocs(q);
    return querySnapshot.docs.map(doc => ({ id: doc.id, ...doc.data() }));
  } catch (error) {
    console.error('Error fetching reservations:', error);
    return [];
  }
}

async function updateReservationStatus(reservationId, status) {
  const db = await window.getFirebaseDb();
  const { doc, updateDoc } = await import('https://www.gstatic.com/firebasejs/12.13.0/firebase-firestore.js');

  try {
    await updateDoc(doc(db, 'reservations', reservationId), { status });
  } catch (error) {
    console.error('Error updating reservation:', error);
    throw error;
  }
}

// ===== MESSAGES (Concierge Chat) =====
async function sendMessage(reservationId, senderId, senderName, text, senderType = 'guest') {
  const db = await window.getFirebaseDb();
  const { collection, addDoc, serverTimestamp } = await import('https://www.gstatic.com/firebasejs/12.13.0/firebase-firestore.js');

  try {
    const docRef = await addDoc(collection(db, 'messages'), {
      reservationId,
      senderId,
      senderName,
      senderType, // 'guest' or 'host'
      text,
      read: false,
      createdAt: serverTimestamp(),
    });
    return { id: docRef.id };
  } catch (error) {
    console.error('Error sending message:', error);
    throw error;
  }
}

async function getMessagesByReservation(reservationId) {
  const db = await window.getFirebaseDb();
  const { collection, query, where, orderBy, getDocs } = await import('https://www.gstatic.com/firebasejs/12.13.0/firebase-firestore.js');

  try {
    const q = query(
      collection(db, 'messages'),
      where('reservationId', '==', reservationId),
      orderBy('createdAt', 'asc')
    );
    const querySnapshot = await getDocs(q);
    return querySnapshot.docs.map(doc => ({ id: doc.id, ...doc.data() }));
  } catch (error) {
    console.error('Error fetching messages:', error);
    return [];
  }
}

// ===== PRICING =====
async function getPricing(propertyId) {
  const db = await window.getFirebaseDb();
  const { doc, getDoc } = await import('https://www.gstatic.com/firebasejs/12.13.0/firebase-firestore.js');

  try {
    const docSnap = await getDoc(doc(db, 'pricing', propertyId));
    return docSnap.exists() ? { id: docSnap.id, ...docSnap.data() } : { basePrice: 1500, seasonalAdjustments: {} };
  } catch (error) {
    console.error('Error fetching pricing:', error);
    return { basePrice: 1500 };
  }
}

// ===== GUESTS =====
async function getGuestProfile(guestId) {
  const db = await window.getFirebaseDb();
  const { doc, getDoc } = await import('https://www.gstatic.com/firebasejs/12.13.0/firebase-firestore.js');

  try {
    const docSnap = await getDoc(doc(db, 'guests', guestId));
    return docSnap.exists() ? { id: docSnap.id, ...docSnap.data() } : null;
  } catch (error) {
    console.error('Error fetching guest:', error);
    return null;
  }
}

async function updateGuestProfile(guestId, updates) {
  const db = await window.getFirebaseDb();
  const { doc, updateDoc } = await import('https://www.gstatic.com/firebasejs/12.13.0/firebase-firestore.js');

  try {
    await updateDoc(doc(db, 'guests', guestId), updates);
  } catch (error) {
    console.error('Error updating guest:', error);
    throw error;
  }
}

window.getProperties = getProperties;
window.getPropertyById = getPropertyById;
window.createReservation = createReservation;
window.getReservationsByGuest = getReservationsByGuest;
window.getReservationsByProperty = getReservationsByProperty;
window.updateReservationStatus = updateReservationStatus;
window.sendMessage = sendMessage;
window.getMessagesByReservation = getMessagesByReservation;
window.getPricing = getPricing;
window.getGuestProfile = getGuestProfile;
window.updateGuestProfile = updateGuestProfile;
