const Logo = require("../models/logo.model.js");
const multer = require("multer");
const path = require("path");
const fs = require("fs");

// Ensure image directory exists
const imageDir = path.join(__dirname, "../images/");
if (!fs.existsSync(imageDir)) {
  fs.mkdirSync(imageDir, { recursive: true });
}

// Multer setup
const storage = multer.diskStorage({
  destination: (req, file, cb) => {
    cb(null, imageDir);
  },
  filename: (req, file, cb) => {
    const uniqueName = `${Date.now()}-${file.originalname}`;
    cb(null, uniqueName);
  },
});
const upload = multer({ storage });

// Controller function
const postLogo = async (req, res) => {
  try {
    // Multer middleware to handle file upload
    const uploadMiddleware = upload.fields([{ name: "image", maxCount: 1 }]);
    uploadMiddleware(req, res, async (err) => {
      if (err) return res.status(400).json({ message: err.message });

      const file = req.files?.image?.[0];
      if (!file) {
        return res.status(400).json({ message: "Image file is required" });
      }

      const userId = req.user?.userId;
      if (!userId) {
        return res.status(401).json({ message: "Unauthorized user" });
      }

      const logoData = {
        userId,
        fileName: file.originalname,
        filePath: `images/${file.filename}`, // relative path for later access
      };

      const logo = await Logo.create(logoData);

      res.status(201).json({
        message: "Logo uploaded successfully",
        logo,
      });
    });
  } catch (error) {
    res.status(500).json({ message: error.message });
  }
};

module.exports = { postLogo };
