const mongoose = require("mongoose");
const connectDB = require("../config/database");
const Home = require("../models/home");

const DEFAULT_ICON_BY_PLATFORM = {
  facebook: "/uploads/home/floating-contact/Facebook_Logo_Primary.webp",
  zalo: "/uploads/home/floating-contact/Icon_of_Zalo.svg.webp",
};

async function up() {
  await connectDB();

  try {
    const homes = await Home.find({
      floatingContact: { $exists: true },
    });

    let updatedCount = 0;

    for (const home of homes) {
      const floatingContact = home.floatingContact || {};
      let modified = false;

      if (!floatingContact.trigger) {
        floatingContact.trigger = {};
        modified = true;
      }

      if (typeof floatingContact.trigger.imageSrc !== "string") {
        floatingContact.trigger.imageSrc = "";
        modified = true;
      }

      if (Array.isArray(floatingContact.actions)) {
        floatingContact.actions = floatingContact.actions.map((action) => {
          const defaultIcon =
            DEFAULT_ICON_BY_PLATFORM[String(action?.platform || "").trim().toLowerCase()] || "";

          if (typeof action?.iconImage !== "string") {
            modified = true;
            return {
              ...action,
              iconImage: defaultIcon,
            };
          }

          if (!action.iconImage.trim() && defaultIcon) {
            modified = true;
            return {
              ...action,
              iconImage: defaultIcon,
            };
          }

          return action;
        });
      }

      if (modified) {
        home.floatingContact = floatingContact;
        home.markModified("floatingContact");
        await home.save();
        updatedCount += 1;
      }
    }

    console.log(
      `Added floatingContact trigger/action image fields to ${updatedCount} Home document(s).`,
    );
  } catch (error) {
    console.error("Failed to add floatingContact icon image fields:", error);
    throw error;
  } finally {
    await mongoose.disconnect();
  }
}

async function down() {
  await connectDB();

  try {
    const homes = await Home.find({
      floatingContact: { $exists: true },
    });

    let updatedCount = 0;

    for (const home of homes) {
      const floatingContact = home.floatingContact || {};
      let modified = false;

      if (floatingContact.trigger && "imageSrc" in floatingContact.trigger) {
        delete floatingContact.trigger.imageSrc;
        modified = true;
      }

      if (Array.isArray(floatingContact.actions)) {
        floatingContact.actions = floatingContact.actions.map((action) => {
          if (!action || !("iconImage" in action)) {
            return action;
          }

          modified = true;
          const nextAction = { ...action };
          delete nextAction.iconImage;
          return nextAction;
        });
      }

      if (modified) {
        home.floatingContact = floatingContact;
        home.markModified("floatingContact");
        await home.save();
        updatedCount += 1;
      }
    }

    console.log(
      `Removed floatingContact trigger/action image fields from ${updatedCount} Home document(s).`,
    );
  } catch (error) {
    console.error("Failed to rollback floatingContact icon image fields:", error);
    throw error;
  } finally {
    await mongoose.disconnect();
  }
}

module.exports = { up, down };
