import fs from 'fs'
import { authApi } from '../../../api/api.jsx'

const DELETE = async (req, res) => {
  console.log("req.method: ", req.body)
  console.log("req.method: ", req.method)
  try {
    let role = ""
    if (req.body.role) role = req.body.role
    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) {

      console.log("req", req.body)
      if (!req.body.path || !req.body.item) throw "Failed"
      const path = "../.ec_uploads/" + process.env.NEXT_PUBLIC_COMPANY_ID + "/" + req.body.path;
      const deleteItem = req.body.item;
      if (deleteItem.length > 0) {
        for (const item of deleteItem) {
          if (item)
            await fs.promises.rm(path + item, {
              recursive: true,
            }).catch((err) => {
              console.log(err)
            })
        }
      }
      res.status(200).json({ success: true });
    }
  } catch (err) {
    console.log("err", err)
    res.status(500).json({ success: false, message: "Failed" });
  }
}



export default DELETE