const { digitalmarketingServiceTemplateModel , digitalmarketingServiceTemplate } = require("../../models/services_templates/digitalmarketingServiceTemplateModel");
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 digitalmarketingServiceTemplateController = {
  createTemplate: async (req, res) => {
    try {
      const newData = await digitalmarketingServiceTemplateModel.create(req.body);
      return res.status(201).json({
        success: true,
        message: "Digital Marketing Service 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 digitalmarketingServiceTemplateModel.findAll({
      order: [["created_at", "DESC"]],
    });

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

      // Helper to parse JSON and add base URL to specified image fields
      const parseAndFix = (data, imageKeys = []) => {
        const parsed = parseSafe(data);
        if (parsed && imageKeys.length) {
          imageKeys.forEach(key => {
            if (Array.isArray(parsed[key])) {
              parsed[key] = parsed[key].map(item => ({
                ...item,
                image: item.image ? withBaseUrl(item.image) : item.image,
                image_url: item.image_url ? withBaseUrl(item.image_url) : item.image_url,
                icon_url: item.icon_url ? withBaseUrl(item.icon_url) : item.icon_url
              }));
            } else if (parsed[key]) {
              parsed[key] = withBaseUrl(parsed[key]);
            }
          });
        }
        return parsed;
      };

      const banner = parseAndFix(t.banner, ["background_image_url"]);
      if (banner?.background_image_url) {
        banner.background_image_url = withBaseUrl(banner.background_image_url);
      }

      const standOut = parseAndFix(t.stand_out_section, ["background_file_url", "image"]);

      const ourServices = parseAndFix(t.our_services_section, ["section_background"]);
      if (ourServices?.services) {
        ourServices.services = ourServices.services.map(s => ({
          ...s,
          image_url: withBaseUrl(s.image_url),
          sub_services: s.sub_services?.map(sub => ({
            ...sub,
            icon_url: withBaseUrl(sub.icon_url),
          })) || [],
        }));
      }

      const industriesWeServe = parseAndFix(t.industries_we_serve_section);
      if (industriesWeServe?.industries) {
        industriesWeServe.industries = industriesWeServe.industries.map(i => ({
          ...i,
          image_url: withBaseUrl(i.image_url),
        }));
      }

      const topClients = parseAndFix(t.our_top_clients_section);
      if (topClients?.clients) {
        topClients.clients = topClients.clients.map(client => ({
          ...client,
          image_url: withBaseUrl(client.image_url),
        }));
      }

      const portfolio = parseAndFix(t.portfolio_section);
      if (portfolio?.projects) {
        portfolio.projects = portfolio.projects.map(p => ({
          ...p,
          image_url: withBaseUrl(p.image_url),
        }));
      }

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

      const infoCards = parseAndFix(t.info_cards_section);
      if (infoCards?.cards) {
        infoCards.cards = infoCards.cards.map(c => ({
          ...c,
          image: withBaseUrl(c.image),
        }));
      }

      const technologies = parseAndFix(t.technologies_we_work_with);
      if (technologies?.service_tab) {
        technologies.service_tab = technologies.service_tab.map(tab => ({
          ...tab,
          features: tab.features?.map(f => ({
            ...f,
            image: withBaseUrl(f.image),
          })) || [],
        }));
      }

      const servicesCards = parseAndFix(t.services_cards);
      if (servicesCards?.cards) {
        servicesCards.cards = servicesCards.cards.map(c => ({
          ...c,
          image: withBaseUrl(c.image),
        }));
      }

      const serviceTabs = parseAndFix(t.service_section_Tabs);
      if (serviceTabs?.tabs) {
        serviceTabs.tabs = serviceTabs.tabs.map(tab => ({
          ...tab,
          image: withBaseUrl(tab.image),
        }));
      }

      const allServicesGrid = parseAndFix(t.all_services_grid);

      return {
        ...t,
        image: t.image ? withBaseUrl(t.image) : null,
        banner,
        stand_out_section: standOut,
        our_services_section: ourServices,
        industries_we_serve_section: industriesWeServe,
        our_top_clients_section: topClients,
        portfolio_section: portfolio,
        our_achievements_section: achievements,
        info_cards_section: infoCards,
        technologies_we_work_with: technologies,
        services_cards: servicesCards,
        service_section_Tabs: serviceTabs,
        all_services_grid: allServicesGrid
      };
    });

    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 digitalmarketingServiceTemplateModel.findByPk(id);
    if (!template) {
      return res.status(404).json({ success: false, message: "Template not found" });
    }

    const t = template.toJSON();

    const parseAndFix = (data, imageKeys = []) => {
      const parsed = parseSafe(data);
      if (parsed && imageKeys.length) {
        imageKeys.forEach(key => {
          if (Array.isArray(parsed[key])) {
            parsed[key] = parsed[key].map(item => ({
              ...item,
              image: item.image ? withBaseUrl(item.image) : item.image,
              image_url: item.image_url ? withBaseUrl(item.image_url) : item.image_url,
              icon_url: item.icon_url ? withBaseUrl(item.icon_url) : item.icon_url
            }));
          } else if (parsed[key]) {
            parsed[key] = withBaseUrl(parsed[key]);
          }
        });
      }
      return parsed;
    };

    const banner = parseAndFix(t.banner, ["background_image_url"]);
    if (banner?.background_image_url) {
      banner.background_image_url = withBaseUrl(banner.background_image_url);
    }

    const standOut = parseAndFix(t.stand_out_section, ["background_file_url", "image"]);

    const ourServices = parseAndFix(t.our_services_section, ["section_background"]);
    if (ourServices?.services) {
      ourServices.services = ourServices.services.map(s => ({
        ...s,
        image_url: withBaseUrl(s.image_url),
        sub_services: s.sub_services?.map(sub => ({
          ...sub,
          icon_url: withBaseUrl(sub.icon_url),
        })) || [],
      }));
    }

    const industriesWeServe = parseAndFix(t.industries_we_serve_section);
    if (industriesWeServe?.industries) {
      industriesWeServe.industries = industriesWeServe.industries.map(i => ({
        ...i,
        image_url: withBaseUrl(i.image_url),
      }));
    }

    const topClients = parseAndFix(t.our_top_clients_section);
    if (topClients?.clients) {
      topClients.clients = topClients.clients.map(client => ({
        ...client,
        image_url: withBaseUrl(client.image_url),
      }));
    }

    const portfolio = parseAndFix(t.portfolio_section);
    if (portfolio?.projects) {
      portfolio.projects = portfolio.projects.map(p => ({
        ...p,
        image_url: withBaseUrl(p.image_url),
      }));
    }

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

    const infoCards = parseAndFix(t.info_cards_section);
    if (infoCards?.cards) {
      infoCards.cards = infoCards.cards.map(c => ({
        ...c,
        image: withBaseUrl(c.image),
      }));
    }

    const technologies = parseAndFix(t.technologies_we_work_with);
    if (technologies?.service_tab) {
      technologies.service_tab = technologies.service_tab.map(tab => ({
        ...tab,
        features: tab.features?.map(f => ({
          ...f,
          image: withBaseUrl(f.image),
        })) || [],
      }));
    }

    const servicesCards = parseAndFix(t.services_cards);
    if (servicesCards?.cards) {
      servicesCards.cards = servicesCards.cards.map(c => ({
        ...c,
        image: withBaseUrl(c.image),
      }));
    }

    const serviceTabs = parseAndFix(t.service_section_Tabs);
    if (serviceTabs?.tabs) {
      serviceTabs.tabs = serviceTabs.tabs.map(tab => ({
        ...tab,
        image: withBaseUrl(tab.image),
      }));
    }

    const allServicesGrid = parseAndFix(t.all_services_grid);

      const get_reviews_url = `digital-marketing-service-template/${id}`;
      const reviews = await reviews_faq_filterController.filterReviewsByRoute(get_reviews_url);

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

    const parsed = {
      ...t,
      image: t.image ? withBaseUrl(t.image) : null,
      banner,
      stand_out_section: standOut,
      our_services_section: ourServices,
      industries_we_serve_section: industriesWeServe,
      our_top_clients_section: topClients,
      portfolio_section: portfolio,
      our_achievements_section: achievements,
      info_cards_section: infoCards,
      technologies_we_work_with: technologies,
      services_cards: servicesCards,
      service_section_Tabs: serviceTabs,
      all_services_grid: allServicesGrid,
      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 digitalmarketingServiceTemplateModel.findByPk(id);
      if (!existing) {
        return res.status(404).json({ success: false, message: "Template not found" });
      }

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

      return res.status(200).json({
        success: true,
        message: "Digital Marketing Service 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 digitalmarketingServiceTemplateModel.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 = digitalmarketingServiceTemplateController;
