import { sessionOptions } from "@/lib/session";
import { app } from "@/firebase";
import { collection, doc, documentId, getDoc, getDocs, getFirestore, query, where } from "firebase/firestore";
import { withIronSessionApiRoute } from "iron-session/next";
import { NextApiRequest, NextApiResponse } from "next";

const db = getFirestore(app);

export default withIronSessionApiRoute(handler, sessionOptions);

async function handler(req: NextApiRequest, res: NextApiResponse) {
    if (!req.session.user) {
        res.status(401).json({ ok: false });
        return;
    }
    if (req.method === "GET") return get(req, res);
}


async function get(req: NextApiRequest, res: NextApiResponse) {
    try {
        const { ids } = req.query;

        if (!ids || !Array.isArray(ids)) {
            return res.status(400).json({ message: 'Invalid or missing ids!' });
        }

        const walkthroughCollection = collection(db, 'walkthrough');

        const q = query(walkthroughCollection, where(documentId(), 'in', ids));

        const querySnapshot = await getDocs(q);

        const documents = querySnapshot.docs.map(doc => ({
            id: doc.id,
            ...doc.data()
        }));

        res.status(200).json(documents);
    } catch (error) {
        console.error('Error fetching data:', error);
        res.status(500).json({ message: 'An unexpected error occurred' });
    }
}
