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

const getAllGallery = async (req, res) => {
  try {
    const data = await galleryDbService.getAllGallery();
    const baseURL = `${req.protocol}://${req.get("host")}/gallery-upload/`;

    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 addGalleryImages = 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 galleryDbService.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 { idGallery } = req.params;
    await galleryDbService.deleteImage(idGallery);
    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 galleryDbService.getAllGallery();
    const baseURL = `${req.protocol}://${req.get("host")}/gallery-upload/`;

    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 = {
  getAllGallery,
  addGalleryImages,
  deleteImage,
  getForDashall,
};
