const { parse } = require("dotenv");
const { softwaredevelopmentTemplate , softwaredevelopmentTemplateModel } = require("../../models/services_templates/softwaredevelopmentTemplateModel");
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 softwaredevelopmentTemplateController = {
  createTemplate: async (req, res) => {
    try {
      const newData = await softwaredevelopmentTemplateModel.create(req.body);
      return res.status(201).json({
        success: true,
        message: "Software Development 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 softwaredevelopmentTemplateModel.findAll({
      order: [["created_at", "DESC"]],
    });

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

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

      t.services_tabs_section_image = withBaseUrl(t.services_tabs_section_image);

      t.services_tab_section = parseSafe(t.services_tab_section);
      if (Array.isArray(t.services_tab_section?.services)) {
        t.services_tab_section.services = t.services_tab_section.services.map(item => ({
          ...item,
          icon_url: withBaseUrl(item.icon_url),
        }));
      }

      t.info_cards_section = parseSafe(t.info_cards_section);
      if (Array.isArray(t.info_cards_section?.cards)) {
        t.info_cards_section.cards = t.info_cards_section.cards.map(card => ({
          ...card,
          image: withBaseUrl(card.image),
        }));
      }

      t.our_services_section = parseSafe(t.our_services_section);
      t.all_services_grid = parseSafe(t.all_services_grid);
      t.services_tabs_section_text = parseSafe(t.services_tabs_section_text);


      return t;
    });

    return res.status(200).json({
      success: true,
      message: "Software Development templates fetched successfully",
      data: parsedTemplates,
    });
  } catch (error) {
    console.error("Get All 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 softwaredevelopmentTemplateModel.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 servicesTab = parseSafe(t.services_tab_section);
    if (Array.isArray(servicesTab?.services)) {
      servicesTab.services = servicesTab.services.map(item => ({
        ...item,
        icon_url: withBaseUrl(item.icon_url),
      }));
    }

    const infoCards = parseSafe(t.info_cards_section);
    if (Array.isArray(infoCards?.cards)) {
      infoCards.cards = infoCards.cards.map(card => ({
        ...card,
        image: withBaseUrl(card.image),
      }));
    }

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

      const get_faqs = `software-development-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),
      services_tab_section: servicesTab,
      info_cards_section: infoCards,
      services_tabs_section_text: parseSafe(t.services_tabs_section_text),
      our_services_section: parseSafe(t.our_services_section),
      all_services_grid: parseSafe(t.all_services_grid),
      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 softwaredevelopmentTemplateModel.findByPk(id);
      if (!existing) {
        return res.status(404).json({ success: false, message: "Template not found" });
      }

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

      return res.status(200).json({
        success: true,
        message: "Graphic Designing 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 softwaredevelopmentTemplateModel.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 = softwaredevelopmentTemplateController;
