import models from "$models/index.js";
import { uploadFilesMiddleware } from "$middlewares/index.js";
import multerErrors from "./multer-errors.js";

import fs from "fs";

export const GET_FILE = (req, res) => {
  const { id } = req.params;

  models.file
    .findById(id)
    .then((file) => {
      if (file) {
        res.contentType(file.type);
        res.send(file.content);
      } else {
        res.status(404).send({ message: "file did not found" });
      }
    })
    .catch((error) => {});
};

export const UPLOAD = async (req, res) => {
  try {
    await uploadFilesMiddleware(req, res);

    if (!req.file) {
      return res.status(400).send({ message: "فایل آپلود نشده است" });
    }

    const img = fs.readFileSync(req.file.path);
    const encodeImg = img.toString("base64");
    const trimmedName =
      typeof req.body?.name === "string" ? req.body.name.trim() : "";
    const finalImg = {
      content: Buffer.from(encodeImg, "base64"),
      type: req.file.mimetype,
      extension: req.file.originalname.split(".").pop(),
    };
    if (trimmedName) {
      finalImg.name = trimmedName;
    }

    const result = await models.file.create(finalImg);
    fs.unlinkSync(req.file.path);

    return res.status(200).send({ file: result });
  } catch (error) {
    const message =
      error && error.code && multerErrors[error.code]
        ? multerErrors[error.code]
        : error.message || "مشکلی در ارتباط با سرور وجود دارد";

    if (req.file?.path && fs.existsSync(req.file.path)) {
      fs.unlinkSync(req.file.path);
    }

    return res.status(400).send({ message, errorCode: error.code });
  }
};

export const DELETE = (req, res) => {
  const _id = req.params.id;

  models.file
    .findByIdAndDelete(_id)
    .then((upload) => {
      if (upload) {
        res.status(200).send({ message: "فایل مورد نظر با موفقیت حذف شد." });
      } else {
        res.status(404).send({ message: "فایل مورد نظر پیدا نشد." });
      }
    })
    .catch((error) => {
      res.status(500).send({ message: error.message });
    });
};
