const { parse } = require("dotenv");
const {  searchenginemarketingTemplate, searchenginemarketingTemplateModel } = require("../../models/services_templates/searchenginemarketingTemplateModel");
require("dotenv").config();

const reviews_faq_filterController = require("./reviews_faqs_filter/reviews_faq_filterController");



const withBaseUrl = (path) => {
  if (!path) return path;
  if (path.startsWith("http")) return path;
  return `${BASE_URL}${path}`;
};

const parseSafe = (json) => {
  try {
    return typeof json === 'string' ? JSON.parse(json) : json;
  } catch {
    return null;
  }
};

const BASE_URL = process.env.BASE_URL;

const searchenginemarketingTemplateController = {
  createTemplate: async (req, res) => {
    try {
      const newData = await searchenginemarketingTemplateModel.create(req.body);
      return res.status(201).json({
        success: true,
        message: "Search Engine Marketing Template created!",
        data: newData,
      });
    } catch (error) {
      console.error("Create Error:", error);
      return res.status(500).json({ success: false, message: "Server Error", error });
    }
  },


getAllTemplates: async (req, res) => {
  try {
    const templates = await searchenginemarketingTemplateModel.findAll({
      order: [["created_at", "DESC"]],
    });

    const parsedTemplates = templates.map(template => {
      const t = template.toJSON();

      const banner = parseSafe(t.banner);
      if (banner?.background_image_url) {
        banner.background_image_url = withBaseUrl(banner.background_image_url);
      }

      const standOut = parseSafe(t.stand_out_section);
      if (standOut?.background_file_url) {
        standOut.background_file_url = withBaseUrl(standOut.background_file_url);
      }
      if (standOut?.image) {
        if (Array.isArray(standOut.image)) {
          standOut.image = standOut.image.map(img => withBaseUrl(img));
        } else {
          standOut.image = withBaseUrl(standOut.image);
        }
      }

      const ourServices = parseSafe(t.our_services_section);
      if (ourServices?.section_background) {
        ourServices.section_background = withBaseUrl(ourServices.section_background);
      }
      if (ourServices?.services_cards) {
        ourServices.services_cards = ourServices.services_cards.map(s => ({
          ...s,
          icon_url: withBaseUrl(s.icon_url),
        }));
      }

      const achievements = parseSafe(t.our_achievements_section);
      if (achievements?.features) {
        achievements.features = achievements.features.map(f => ({
          ...f,
          icon_url: withBaseUrl(f.icon_url),
        }));
      }

      const technologiesSection = parseSafe(t.technnologies_section);
      if (technologiesSection?.image_url) {
        technologiesSection.image_url = withBaseUrl(technologiesSection.image_url);
      }

      const ourExperties = parseSafe(t.our_experties);
      if (Array.isArray(ourExperties?.sections_cards)) {
        ourExperties.sections_cards = ourExperties.sections_cards.map(card => ({
          ...card,
          icon_url: withBaseUrl(card.icon_url),
        }));
      }

      const aboutUs = parseSafe(t.about_us);
      if (aboutUs?.section_background) {
        aboutUs.section_background = withBaseUrl(aboutUs.section_background);
      }

      return {
        ...t,
        banner,
        stand_out_section: standOut,
        our_services_section: ourServices,
        our_achievements_section: achievements,
        technnologies_section: technologiesSection,
        our_experties: ourExperties,
        about_us: aboutUs,
      };
    });

    return res.status(200).json({ success: true, data: parsedTemplates });
  } catch (error) {
    console.error("Fetch Error:", error);
    return res.status(500).json({ success: false, message: "Server Error", error });
  }
},

getTemplateById: async (req, res) => {
  try {
    const id = req.params.id;
    const template = await searchenginemarketingTemplateModel.findByPk(id);
    if (!template) {
      return res.status(404).json({ success: false, message: "Template not found" });
    }

    const t = template.toJSON();

    const banner = parseSafe(t.banner);
    if (banner?.background_image_url) {
      banner.background_image_url = withBaseUrl(banner.background_image_url);
    }

    const standOut = parseSafe(t.stand_out_section);
    if (standOut?.background_file_url) {
      standOut.background_file_url = withBaseUrl(standOut.background_file_url);
    }
    if (standOut?.image) {
      if (Array.isArray(standOut.image)) {
        standOut.image = standOut.image.map(img => withBaseUrl(img));
      } else {
        standOut.image = withBaseUrl(standOut.image);
      }
    }

    const ourServices = parseSafe(t.our_services_section);
    if (ourServices?.section_background) {
      ourServices.section_background = withBaseUrl(ourServices.section_background);
    }
    if (ourServices?.services_cards) {
      ourServices.services_cards = ourServices.services_cards.map(s => ({
        ...s,
        icon_url: withBaseUrl(s.icon_url),
      }));
    }

    const achievements = parseSafe(t.our_achievements_section);
    if (achievements?.features) {
      achievements.features = achievements.features.map(f => ({
        ...f,
        icon_url: withBaseUrl(f.icon_url),
      }));
    }

    const technologiesSection = parseSafe(t.technnologies_section);
    if (technologiesSection?.image_url) {
      technologiesSection.image_url = withBaseUrl(technologiesSection.image_url);
    }

    const ourExperties = parseSafe(t.our_experties);
    if (Array.isArray(ourExperties?.sections_cards)) {
      ourExperties.sections_cards = ourExperties.sections_cards.map(card => ({
        ...card,
        icon_url: withBaseUrl(card.icon_url),
      }));
    }

    const aboutUs = parseSafe(t.about_us);
    if (aboutUs?.section_background) {
      aboutUs.section_background = withBaseUrl(aboutUs.section_background);
    }
    
      const get_reviews_url = `search-engine-marketing-service-template/${id}`;
      const reviews = await reviews_faq_filterController.filterReviewsByRoute(get_reviews_url);

      const get_faqs = `search-engine-marketing-service-template/${id}`;
      const faqs = await reviews_faq_filterController.getFaqForPage(get_faqs);

    const parsed = {
      ...t,
      banner,
      stand_out_section: standOut,
      our_services_section: ourServices,
      our_achievements_section: achievements,
      technnologies_section: technologiesSection,
      our_experties: ourExperties,
      about_us: aboutUs,
      reviews: reviews,
      faqs: faqs
    };

    return res.status(200).json({ success: true, data: parsed });
  } catch (error) {
    console.error("Get By ID Error:", error);
    return res.status(500).json({ success: false, message: "Server Error", error });
  }
},





  updateTemplate: async (req, res) => {
    try {
      const id = req.params.id;
      const existing = await searchenginemarketingTemplateModel.findByPk(id);
      if (!existing) {
        return res.status(404).json({ success: false, message: "Template not found" });
      }

      await searchenginemarketingTemplateModel.update(req.body, { where: { id } });
      const updated = await searchenginemarketingTemplateModel.findByPk(id);

      return res.status(200).json({
        success: true,
        message: "Search Engine Marketing Template updated!",
        data: updated,
      });
    } catch (error) {
      console.error("Update Error:", error);
      return res.status(500).json({ success: false, message: "Server Error", error });
    }
  },

  deleteTemplate: async (req, res) => {
    try {
      const id = req.params.id;
      const deleted = await searchenginemarketingTemplateModel.destroy({ where: { id } });

      if (!deleted) {
        return res.status(404).json({ success: false, message: "Template not found" });
      }

      return res.status(200).json({
        success: true,
        message: "Template deleted successfully!",
      });
    } catch (error) {
      console.error("Delete Error:", error);
      return res.status(500).json({ success: false, message: "Server Error", error });
    }
  },
};

module.exports = searchenginemarketingTemplateController
