import { NextResponse } from "next/server";
import { Formidable } from "formidable";
import fs from 'fs'
import { authApi } from '../../../api/api.jsx'

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

const POST = async (req, res) => {
  try {
    const form = new Formidable();
    await form.parse(req, async (err, fields, files) => {
      console.log("fields:", fields)
      let role = ""
      if (fields.role && fields.role.length > 0) role = fields.role[0]
      console.log("req.headers: ", req.headers);
      let isAuthSuccess = false
      if (role === "reseller") {
        await authApi
          .post(
            "/reseller/middleware",
            {},
            { headers: { Authorization: `${req.headers.authorization}` } }
          )
          .then(async (response) => {
            console.log("response.data,", response.data);
            if (response.data.authorize === true) {
              isAuthSuccess = true
            } else {
              res.status(401).json({ success: false, message: "Authentication Failed" });
            }
          })
          .catch((err) => {
            console.log("response: ", err);
            res.status(401).json({ success: false, message: "Authentication Failed" });
          });
      } else {
        await authApi
          .post(
            "/product/middleware",
            {},
            { headers: { Authorization: `${req.headers.authorization}` } }
          )
          .then(async (response) => {
            console.log("response.data,", response.data);
            if (response.data.authorize === true) {
              isAuthSuccess = true
            } else {
              res.status(401).json({ success: false, message: "Authentication Failed" });
            }
          })
          .catch((err) => {
            console.log("response: ", err);
            res.status(401).json({ success: false, message: "Authentication Failed" });
          });
      }
      if (isAuthSuccess) {
        // Auth Success
        let fileName = []


        for (const index in files) {
          const file = files[index][0];
          const dir = "../.ec_uploads/" + process.env.NEXT_PUBLIC_COMPANY_ID + "/" + fields.path.toString();
          console.log(":dir ", dir)
          if (!fs.existsSync(dir)) {
            console.log("not availble");
            fs.mkdirSync(dir, { recursive: true });
          }
          let name =
            file.originalFilename
          const newPath = `${dir}${name}`;
          var oldpath = file.filepath;
          await fs.promises.cp(oldpath, newPath, {
            recursive: true,
          })
          await fs.promises.rm(oldpath, {
            recursive: true,
          })
          fileName.push(name);
          res.status(200).json({ success: true, images: fileName });
        }
        if (err) reject({ err })


      }
    })

  } catch (err) {
    console.log("err", err)
    res.status(500).json({ success: false, message: "Failed" });
  }
}



export default POST