// Next.js API route support: https://nextjs.org/docs/api-routes/introduction
import type {NextApiRequest, NextApiResponse} from "next";
import {withIronSessionApiRoute} from "iron-session/next";
import {sessionOptions} from "@/lib/session";
import {getDownloadURL, getStorage, ref} from "firebase/storage";
import {app, storage} from "@/firebase";
import axios from "axios";

export default withIronSessionApiRoute(handler, sessionOptions);

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

	const {path} = req.body as {path: string};

	const pathReference = ref(storage, path);
	const url = await getDownloadURL(pathReference);

	const response = await axios.get(url, {responseType: "arraybuffer"});

	res.status(200).send(response.data);
}
