const { addBaseUrlToImages } = require("../utils/imageHelper");
const Home = require("../models/home");
const writeAuditLog = require("../audit/writeAuditLog");
const diffObject = require("../audit/diffObject");
const AUDIT_ACTIONS = require("../constants/auditAction");

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

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

// Render admin view
exports.index = async (req, res) => {
  try {
    const data = (await getTestimonialData()) || {
      heading: "Student Reviews & Testimonials",
      subheading: "What Our Students Say",
      videoUrl: "",
      videoThumbnail: "",
      items: [],
    };

    const frontendUrl = process.env.FRONTEND_URL;

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

// Cập nhật dữ liệu testimonial (chỉ update phần testimonials của Home)
exports.update = async (req, res) => {
  try {
    const { heading, subheading, videoUrl, videoThumbnail, items } = req.body;

    // Parse JSON strings nếu cần
    const parseJson = (data) => {
      if (!data) return null;
      if (typeof data === "string") {
        try {
          return JSON.parse(data);
        } catch (e) {
          return null;
        }
      }
      return data;
    };

    const itemsData = parseJson(items);

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

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

    // ✅ Capture BEFORE state
    const beforeData = home.testimonials
      ? JSON.parse(
          JSON.stringify(
            home.testimonials.toObject
              ? home.testimonials.toObject()
              : home.testimonials,
          ),
        )
      : {};

    const updatedTestimonialData = {
      heading: heading || "Student Reviews & Testimonials",
      subheading: subheading || "What Our Students Say",
      videoUrl: videoUrl || "",
      videoThumbnail: videoThumbnail || "",
      items: itemsData || [],
    };

    // Cập nhật chỉ phần testimonials
    home.testimonials = updatedTestimonialData;

    await home.save();

    // ✅ Capture AFTER state
    const afterData = JSON.parse(JSON.stringify(updatedTestimonialData));

    // ✅ AUDIT LOGGING - Testimonial Updated
    const changes = diffObject(beforeData, afterData);
    if (changes.length > 0) {
      await writeAuditLog({
        model: "Home",
        documentId: home._id,
        action: AUDIT_ACTIONS.UPDATE_TESTIMONIAL,
        before: beforeData,
        after: afterData,
        changes,
        req,
      });
    }

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