const { parse } = require("dotenv");
const { internetMarketingTemplate , internetMarketingTemplateModel  } = require("../../models/services_templates/internetmarketingTemplateModel");
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 internetmarketingTemplateController = {
  createTemplate: async (req, res) => {
    try {
      const newData = await internetMarketingTemplateModel.create(req.body);
      return res.status(201).json({
        success: true,
        message: "Internet 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 internetMarketingTemplateModel.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 servicesTabs = parseSafe(t.services_tabs_section_image);
      if (servicesTabs?.services_tabs_section_image)
        servicesTabs.services_tabs_section_image = withBaseUrl(servicesTabs.services_tabs_section_image);

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

      const infoCard = parseSafe(t.information_card);
      if (infoCard?.cards) {
        infoCard.cards = infoCard.cards.map(c => ({
          ...c,
          image_url: withBaseUrl(c.image_url),
        }));
      }

      const techUsed = parseSafe(t.technnology_used);
      if (techUsed?.sections_cards) {
        techUsed.sections_cards = techUsed.sections_cards.map(section => ({
          ...section,
          related_technologies: section.related_technologies?.map(rt => ({
            ...rt,
            icon_url: withBaseUrl(rt.icon_url),
          })) || [],
        }));
      }

      const ourExperties = parseSafe(t.our_experties_section);
      if (ourExperties?.image) ourExperties.image = withBaseUrl(ourExperties.image);
      if (ourExperties?.background_image_url) ourExperties.background_image_url = withBaseUrl(ourExperties.background_image_url);

      return {
        ...t,
        banner,
        services_tabs_section_image: servicesTabs,
        stand_out_section: standOut,
        information_card: infoCard,
        technnology_used: techUsed,
        our_experties_section: ourExperties,
      };
    });

    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 internetMarketingTemplateModel.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 servicesTabs = parseSafe(t.services_tabs_section_image);
    if (servicesTabs?.services_tabs_section_image)
      servicesTabs.services_tabs_section_image = withBaseUrl(servicesTabs.services_tabs_section_image);

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

    const infoCard = parseSafe(t.information_card);
    if (infoCard?.cards) {
      infoCard.cards = infoCard.cards.map(c => ({
        ...c,
        image_url: withBaseUrl(c.image_url),
      }));
    }

    const techUsed = parseSafe(t.technnology_used);
    if (techUsed?.sections_cards) {
      techUsed.sections_cards = techUsed.sections_cards.map(section => ({
        ...section,
        related_technologies: section.related_technologies?.map(rt => ({
          ...rt,
          icon_url: withBaseUrl(rt.icon_url),
        })) || [],
      }));
    }

    const ourExperties = parseSafe(t.our_experties_section);
    if (ourExperties?.image) ourExperties.image = withBaseUrl(ourExperties.image);
    if (ourExperties?.background_image_url) ourExperties.background_image_url = withBaseUrl(ourExperties.background_image_url);
    
      const get_reviews_url = `internet-marketing-service-template/${id}`;
      const reviews = await reviews_faq_filterController.filterReviewsByRoute(get_reviews_url);

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

    return res.status(200).json({
      success: true,
      data: {
        ...t,
        banner,
        services_tabs_section_image: servicesTabs,
        stand_out_section: standOut,
        information_card: infoCard,
        technnology_used: techUsed,
        our_experties_section: ourExperties,
        reviews: reviews,
        faqs: faqs
      },
    });
  } 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 internetMarketingTemplateModel.findByPk(id);
      if (!existing) {
        return res.status(404).json({ success: false, message: "Template not found" });
      }

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

      return res.status(200).json({
        success: true,
        message: "Internet 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 internetMarketingTemplateModel.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 = internetmarketingTemplateController;
