const { WebDesignServiceTemplate , WebDesignServiceTemplateModel } = require("../../models/services_templates/WebDesignServiceTemplateModel");
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 WebDesignServiceTemplateController = {
  createTemplate: async (req, res) => {
    try {
      const newData = await WebDesignServiceTemplateModel.create(req.body);
      return res.status(201).json({
        success: true,
        message: "Web Development 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 WebDesignServiceTemplateModel.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 serviceTabs = parseSafe(t.service_section_Tabs);
      const servicesCards = parseSafe(t.services_cards);
      const whyChoose = parseSafe(t.why_choose_us_section);
      const infoCards = parseSafe(t.info_cards_section);

      if (Array.isArray(servicesCards)) {
        servicesCards.forEach(card => {
          card.image = withBaseUrl(card.image);
        });
      }

      if (whyChoose?.our_qualities) {
        whyChoose.our_qualities = whyChoose.our_qualities.map(q => ({ ...q }));
      }

      if (infoCards?.cards) {
        infoCards.cards = infoCards.cards.map(card => ({
          ...card,
          services: card.services.map(service => ({
            ...service,
            image_url: withBaseUrl(service.image_url),
          })),
        }));
      }

      return {
        ...t,
        banner,
        services_tabs_section_image: withBaseUrl(t.services_tabs_section_image),
        service_section_Tabs: serviceTabs,
        services_cards: servicesCards,
        why_choose_us_section: whyChoose,
        info_cards_section: infoCards,
      };
    });

    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 WebDesignServiceTemplateModel.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 serviceTabs = parseSafe(t.service_section_Tabs);
    const servicesCards = parseSafe(t.services_cards);
    const whyChoose = parseSafe(t.why_choose_us_section);
    const infoCards = parseSafe(t.info_cards_section);

    if (Array.isArray(servicesCards)) {
      servicesCards.forEach(card => {
        card.image = withBaseUrl(card.image);
      });
    }

    if (whyChoose?.our_qualities) {
      whyChoose.our_qualities = whyChoose.our_qualities.map(q => ({ ...q }));
    }

    if (infoCards?.cards) {
      infoCards.cards = infoCards.cards.map(card => ({
        ...card,
        services: card.services.map(service => ({
          ...service,
          image_url: withBaseUrl(service.image_url),
        })),
      }));
    }

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

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

    const parsed = {
      ...t,
      banner,
      services_tabs_section_image: withBaseUrl(t.services_tabs_section_image),
      service_section_Tabs: serviceTabs,
      services_cards: servicesCards,
      why_choose_us_section: whyChoose,
      info_cards_section: infoCards,
      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 WebDesignServiceTemplateModel.findByPk(id);
      if (!existing) {
        return res.status(404).json({ success: false, message: "Template not found" });
      }

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

      return res.status(200).json({
        success: true,
        message: "Web Design 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 WebDesignServiceTemplateModel.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 = WebDesignServiceTemplateController;
