// 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 axios, {AxiosResponse} from "axios";
import formidable from "formidable-serverless";
import {getDownloadURL, ref, uploadBytes} from "firebase/storage";
import fs from "fs";
import {app, storage} from "@/firebase";
import {doc, getDoc, getFirestore, setDoc} from "firebase/firestore";
import {Stat} from "@/interfaces/user";
import {speakingReverseMarking} from "@/utils/score";

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;
	}

	const form = formidable({keepExtensions: true});
	await form.parse(req, async (err: any, fields: any, files: any) => {
		if (err) {
			console.log(err);
			return res.status(500).json({ok: false});
		}

		const audioFile = files.audio;
		const audioFileRef = ref(storage, `${fields.root}/${(audioFile as any).path.replace("upload_", "")}`);

		const binary = fs.readFileSync((audioFile as any).path).buffer;
		const snapshot = await uploadBytes(audioFileRef, binary);

		const path = await getDownloadURL(snapshot.ref);
		res.status(200).json({path});
	});
}

export const config = {
	api: {
		bodyParser: false,
	},
};
