import { ref } from 'vue';
import { getFirestore, collection, getDocs } from 'firebase/firestore';
import { app } from '../firebase';
import { CpvCode } from '../models/CpvCode';

const db = getFirestore(app);

export function useCPVCodesSuggestions() {
    const suggestions = ref([]);
    const loading = ref(false);
    const error = ref(null);

    async function fetchAllCPVCodes() {
        loading.value = true;
        error.value = null;
        try {
            const colRef = collection(db, 'cpvcodes');
            const snapshot = await getDocs(colRef);
            suggestions.value = snapshot.docs.map(docSnap => {
                const data = docSnap.data();
                return new CpvCode(data);
            });
        } catch (e) {
            error.value = e;
        } finally {
            loading.value = false;
        }
    }

    return { suggestions, fetchAllCPVCodes, loading, error };
}
