import { sessionOptions } from "@/lib/session";
import client from "@/lib/mongodb";
import { withIronSessionApiRoute } from "iron-session/next";
import { NextApiRequest, NextApiResponse } from "next";

const db = client.db(process.env.MONGODB_DB);

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 docs = await db.collection('walkthrough').find({
            id: { $in: ids }
        }).toArray();

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