import { initializeApp } from "firebase/app";
import { getFirestore, collection, addDoc, getDocs, limit, orderBy, query, where, serverTimestamp } from "firebase/firestore";

const firebaseConfig = {
	apiKey: process.env.FIREBASE_API_KEY,
	authDomain: process.env.FIREBASE_AUTH_DOMAIN,
	projectId: process.env.FIREBASE_PROJECT_ID,
	storageBucket: process.env.FIREBASE_STORAGE_BUCKET,
	messagingSenderId: process.env.FIREBASE_MESSAGING_SENDER_ID,
	appId: process.env.FIREBASE_APP_ID,
};

const firebaseApp = initializeApp(firebaseConfig);
export const db = getFirestore(firebaseApp);

export default firebaseApp;

export async function addScore(username, email, puzzleId, puzzleTheme, timeSeconds, hintsUsed) {
	try {
		const collectionRef = collection(db, "scores");
		const docRef = await addDoc(collectionRef, {
			username: username,
			email: email || "",
			puzzleId: puzzleId,
			puzzleTheme: puzzleTheme,
			timeSeconds: timeSeconds,
			hintsUsed: hintsUsed || 0,
			createdAt: serverTimestamp(),
		});
		return docRef.id;
	} catch (e) {
		console.error("Error adding document: ", e);
		return null;
	}
}

export async function getScores(puzzleId) {
	try {
		const collectionRef = collection(db, "scores");
		const q = query(collectionRef, where("puzzleId", "==", puzzleId), orderBy("timeSeconds", "asc"), orderBy("createdAt", "desc"), limit(20));
		const querySnapshot = await getDocs(q);
		const dataArray = querySnapshot.docs.map((doc) => {
			const data = doc.data();
			return {
				id: doc.id,
				...data,
				createdAt: data.createdAt?.toDate(),
			};
		});
		console.log(dataArray);
		return dataArray;
	} catch (e) {
		console.error("Error adding document: ", e);
		return null;
	}
}
