const { addBaseUrlToImages } = require("../utils/imageHelper");
const Home = require("../models/home");

// Get videoGallery data from Home model
const getVideoGalleryData = async () => {
    const home = await Home.findOne().sort({ updatedAt: -1 });
    if (!home || !home.videoGallery) {
        return null;
    }
    return home.videoGallery.toObject ? home.videoGallery.toObject() : home.videoGallery;
};

// API to get videoGallery data
exports.api = async (req, res) => {
    try {
        const videoGallery = await getVideoGalleryData();
        if (!videoGallery) {
            return res.status(404).json({ error: "Video Gallery data not found" });
        }
        const baseUrl =
            process.env.BACKEND_URL || `${req.protocol}://${req.get("host")}`;
        const processedData = addBaseUrlToImages(videoGallery, baseUrl);
        res.json(processedData);
    } catch (err) {
        console.error("API Error:", err);
        res.status(500).json({ error: "Error loading video gallery data" });
    }
};

// Render admin view
exports.index = async (req, res) => {
    try {
        const data = (await getVideoGalleryData()) || {
            heading: "",
            videoUrl: "",
            thumbnail: "",
        };

        const frontendUrl = process.env.FRONTEND_URL;

        res.render("admin/home/videoGallery/index", {
            title: "Video Gallery Management",
            layout: "layouts/main",
            data,
            frontendUrl,
            currentPath: req.path,
            user: req.session.user,
        });
    } catch (error) {
        console.error("Error in videoGallery index:", error);
        req.flash("error_msg", "An error occurred while loading the page");
        res.redirect("/admin/dashboard");
    }
};

// Cập nhật dữ liệu videoGallery
exports.update = async (req, res) => {
    try {
        const { heading, videoUrl, thumbnail } = req.body;

        // Tìm hoặc tạo Home document
        let home = await Home.findOne().sort({ updatedAt: -1 });

        if (!home) {
            home = new Home({});
        }

        // Cập nhật chỉ phần videoGallery
        home.videoGallery = {
            heading: heading || "",
            videoUrl: videoUrl || "",
            thumbnail: thumbnail || "",
        };

        await home.save();

        req.flash("success_msg", "Video Gallery updated successfully");
        res.redirect("/admin/home/video-gallery");
    } catch (err) {
        console.error("Error updating video gallery:", err);
        req.flash("error_msg", err.message || "Error updating video gallery");
        res.redirect("/admin/home/video-gallery");
    }
};
