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


import type { NextApiRequest, NextApiResponse } from "next";
import { withIronSessionApiRoute } from "iron-session/next";
import { sessionOptions } from "@/lib/session";
import axios from "axios";
import formidable from 'formidable';
import FormData from 'form-data';
import { readFileSync } from 'fs';

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

    try {
        const form = formidable({
          multiples: true,
        });
    
        const [_, files] = await form.parse(req);
        const formData = new FormData();
    
        if (files.exercises?.[0]) {
          const file = files.exercises[0];
          const buffer = readFileSync(file.filepath);
          
          formData.append('exercises', buffer, {
            filename: file.originalFilename!,
            contentType: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
            knownLength: buffer.length
          });
        }
    
        if (files.solutions?.[0]) {
          const file = files.solutions[0];
          const buffer = readFileSync(file.filepath);
          
          formData.append('solutions', buffer, {
            filename: file.originalFilename!,
            contentType: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
            knownLength: buffer.length
          });
        }
    
        const result = await axios.post(
          `${process.env.BACKEND_URL}/${req.query.module}/import${req.query.module == "level" ? '/': ''}`,
          formData,
          {
            headers: {
              Authorization: `Bearer ${process.env.BACKEND_JWT}`,
              ...formData.getHeaders()
            }
          }
        );
    
        return res.status(200).json(result.data);
    
      } catch (error) {
        console.error(error);
        return res.status(500).json({ 
          error: 'Upload failed',
          details: error instanceof Error ? error.message : 'Unknown error'
        });
      }
    }
    