import { sessionOptions } from "@/lib/session";
import axios from "axios";
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);
    if (req.method === "POST") return post(req, res);
}

async function post(req: NextApiRequest, res: NextApiResponse) {
    try {
        const response = await axios.post(`${process.env.BACKEND_URL}/training_content`, req.body, {
            headers: {
                Authorization: `Bearer ${process.env.BACKEND_JWT}`,
            },
        });
        res.status(response.status).json(response.data);
    } catch (error) {
        res.status(500).json({ message: 'An unexpected error occurred' });
    }
}

async function get(req: NextApiRequest, res: NextApiResponse) {
    try {
        const snapshot = await db.collection("training").find({}).toArray();
        res.status(200).json(snapshot);
    } catch (error) {
        console.error('Error fetching data:', error);
        res.status(500).json({ message: 'An unexpected error occurred' });
    }
}

