const memoryDbService = require("../services/memoryDbService");

const getAllMemory = async (req, res) => {
  try {
    const data = await memoryDbService.getAllGallery();
    const baseURL = `${req.protocol}://${req.get("host")}/memory-images/`;

    const data2 = await Promise.all(
      data.map((item) => {
        return baseURL + item.Image;
      })
    );
    res.status(201).json(data2);
  } catch (err) {
    res.status(500).json({
      Status: "Something went wrong when deleting event!",
      error: err.message,
    });
  }
};

const addMemoryImages = async (req, res) => {
  try {
    if (!req.files || req.files.length === 0) {
      return res.status(400).json({ message: "No images uploaded." });
    }

    // Only keep the filenames
    const images = req.files.map((file) => ({
      filename: file.filename,
    }));

    // Save to DB via your service
    const savedImages = await memoryDbService.addGalleryImages(images);

    res.status(201).json({
      success: true,
      message: "Images uploaded successfully.",
      data: savedImages,
    });
  } catch (err) {
    console.error(err);
    res.status(500).json({
      message: "Something went wrong while uploading images.",
      error: err.message,
    });
  }
};

const deleteImage = async (req, res) => {
  try {
    const { idMemory } = req.params;
    await memoryDbService.deleteImage(idMemory);
    res
      .status(201)
      .json({ success: true, message: "Image deletion completed" });
  } catch (err) {
    console.error(err);
    res.status(500).json({
      message: "Something went wrong while uploading images.",
      error: err.message,
    });
  }
};

const getForDashall = async (req, res) => {
  try {
    const data = await memoryDbService.getAllGallery();
    const baseURL = `${req.protocol}://${req.get("host")}/memory-images/`;

    const data2 = await Promise.all(
      data.map((item) => {
        Img_Url = baseURL + item.Image;
        return {
          ...item,
          Img_Url,
        };
      })
    );
    res.status(201).json(data2);
  } catch (err) {
    res.status(500).json({
      Status: "Something went wrong when deleting event!",
      error: err.message,
    });
  }
};

module.exports = {
  getAllMemory,
  addMemoryImages,
  deleteImage,
  getForDashall,
};
