import type { NextApiRequest, NextApiResponse } from "next";
import { withIronSessionApiRoute } from "iron-session/next";
import { sessionOptions } from "@/lib/session";
import axios from "axios";
import queryToURLSearchParams from "@/utils/query.to.url.params";

export default withIronSessionApiRoute(handler, sessionOptions);

async function handler(req: NextApiRequest, res: NextApiResponse) {
  if (req.method === "POST") return post(req, res);

  return res.status(404).json({ ok: false });
}

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

  const queryParams = queryToURLSearchParams(req);
  let endpoint = queryParams.getAll('module').join("/");

  if (endpoint === "listening") {
    const response = await axios.post(
      `${process.env.BACKEND_URL}/${endpoint}/media`,
      req.body,
      {
        headers: {
          Authorization: `Bearer ${process.env.BACKEND_JWT}`,
          Accept: 'audio/mpeg'
        },
        responseType: 'arraybuffer',
      }
    );

    res.writeHead(200, {
      'Content-Type': 'audio/mpeg',
      'Content-Length': response.data.length
    });

    res.end(response.data);
    return;
  }

  if (endpoint === "speaking") {
    const response = await axios.post(
      `${process.env.BACKEND_URL}/${endpoint}/media`,
      req.body,
      {
        headers: {
          Authorization: `Bearer ${process.env.BACKEND_JWT}`,
        }
      }
    );

    res.status(200).json(response.data);
    return;
  }

  return res.status(405).json({ "error": "Method not allowed."});
}
