const { Router } = require("express");
const multer = require("multer");
const { requireAuth } = require("../middleware/auth");
const {
  uploadBrandLogoBuffer,
  uploadCompanyLogoBuffer,
  uploadProductImageBuffer,
} = require("../lib/cloudinary");

const router = Router();

const MAX_BYTES = 5 * 1024 * 1024;

const upload = multer({
  storage: multer.memoryStorage(),
  limits: { fileSize: MAX_BYTES },
  fileFilter: (_req, file, cb) => {
    if (/^image\/(jpeg|png|gif|webp)$/i.test(file.mimetype)) {
      cb(null, true);
      return;
    }
    cb(new Error("Use JPG, PNG, GIF, or WEBP for the logo"));
  },
});

router.post("/brand-logo", requireAuth, (req, res, next) => {
  upload.single("file")(req, res, (err) => {
    if (err instanceof multer.MulterError) {
      if (err.code === "LIMIT_FILE_SIZE") {
        return res.status(400).json({ error: "Logo must be 5MB or smaller" });
      }
      return res.status(400).json({ error: err.message || "Upload failed" });
    }
    if (err) {
      return res.status(400).json({ error: err.message || "Upload failed" });
    }

    const file = req.file;
    if (!file?.buffer?.length) {
      return res.status(400).json({ error: "No file uploaded" });
    }

    Promise.resolve(uploadBrandLogoBuffer(file.buffer, file.mimetype))
      .then((url) => res.json({ url }))
      .catch(next);
  });
});

router.post("/company-logo", requireAuth, (req, res, next) => {
  upload.single("file")(req, res, (err) => {
    if (err instanceof multer.MulterError) {
      if (err.code === "LIMIT_FILE_SIZE") {
        return res.status(400).json({ error: "Logo must be 5MB or smaller" });
      }
      return res.status(400).json({ error: err.message || "Upload failed" });
    }
    if (err) {
      return res.status(400).json({ error: err.message || "Upload failed" });
    }

    const file = req.file;
    if (!file?.buffer?.length) {
      return res.status(400).json({ error: "No file uploaded" });
    }

    Promise.resolve(uploadCompanyLogoBuffer(file.buffer, file.mimetype))
      .then((url) => res.json({ url }))
      .catch(next);
  });
});

router.post("/product-images", requireAuth, (req, res, next) => {
  upload.array("files", 15)(req, res, (err) => {
    if (err instanceof multer.MulterError) {
      if (err.code === "LIMIT_FILE_SIZE") {
        return res.status(400).json({ error: "Each image must be 5MB or smaller" });
      }
      return res.status(400).json({ error: err.message || "Upload failed" });
    }
    if (err) {
      return res.status(400).json({ error: err.message || "Upload failed" });
    }

    const files = req.files;
    if (!Array.isArray(files) || files.length === 0) {
      return res.status(400).json({ error: "No files uploaded" });
    }

    Promise.all(files.map((f) => uploadProductImageBuffer(f.buffer, f.mimetype)))
      .then((urls) => res.json({ urls }))
      .catch(next);
  });
});

module.exports = router;
