import {
  collection,
  query,
  where,
  orderBy,
  limit,
  getDocs,
} from 'firebase/firestore';
import { db } from './firebase.js';

const studentsRef = collection(db, 'students');

/**
 * Search students by name (case-insensitive prefix match).
 * Firestore doesn't support native full-text search, so we use a
 * `nameLower` field stored at write-time and do a range query.
 *
 * Expected document structure:
 *   { name: "John Smith", nameLower: "john smith", classYear: "1985" }
 */
export async function searchStudents(searchTerm) {
  const term = searchTerm.trim().toLowerCase();
  if (!term) return [];

  const end = term + '\uf8ff'; // Unicode high character for prefix range
  const q = query(
    studentsRef,
    where('nameLower', '>=', term),
    where('nameLower', '<=', end),
    orderBy('nameLower'),
    limit(50)
  );

  try {
    const snapshot = await getDocs(q);
    const results = [];
    snapshot.forEach((doc) => {
      results.push({ id: doc.id, ...doc.data() });
    });
    return results;
  } catch (error) {
    console.error('Error searching students:', error);
    return [];
  }
}
