const { parse } = require("dotenv");
const { brandingAgencyTemplate , brandingAgencyTemplateModel } = require("../../models/services_templates/brandingAgencyTemplateModel");
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 brandingAgencyTemplateController = {
  createTemplate: async (req, res) => {
    try {
      const newData = await brandingAgencyTemplateModel.create(req.body);
      return res.status(201).json({
        success: true,
        message: "Branding Agency 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 brandingAgencyTemplateModel.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 why_us_image = t.why_us_image ? withBaseUrl(t.why_us_image) : null;
//       const serviceTabs = parseSafe(t.service_section_Tabs);
//       const allServices = parseSafe(t.all_services_grid);
//       const whyChoose = parseSafe(t.why_choose_us_section);
//       // const infoCards = parseSafe(t.info_cards_section);
//       const stand_out_section_parse = parseSafe(t.stand_out_section);

//       if (whyChoose?.features) {
//         whyChoose.features = whyChoose.features.map(f => ({
//           ...f,
//           image: withBaseUrl(f.image),
//         }));
//       }

//       // if (infoCards?.cards) {
//       //   infoCards.cards = infoCards.cards.map(card => ({
//       //     ...card,
//       //     image: withBaseUrl(card.image),
//       //   }));
//       // }

//       return {
//         ...t,
//         banner,
//         services_tabs_section_image: withBaseUrl(t.services_tabs_section_image),
//         why_us_image:withBaseUrl(why_us_image),
//         stand_out_section: stand_out_section_parse,
//         why_choose_us_section: parseSafe(t.why_choose_us_section),
//         our_services_section: parseSafe(t.our_services_section),
//         service_section_Tabs: serviceTabs,
//         all_services_grid: allServices,
//         why_choose_us: whyChoose,
//       };
//     });

//     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 });
//   }
// },


getAllTemplates: async (req, res) => {
  try {
    const templates = await brandingAgencyTemplateModel.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 why_us_image = withBaseUrl(t.why_us_image);
      const serviceTabs = parseSafe(t.service_section_Tabs);
      const allServices = parseSafe(t.all_services_grid);
      const stand_out_section_parse = parseSafe(t.stand_out_section);

      const whyChoose = parseSafe(t.why_choose_us_section);
      if (whyChoose?.features) {
        whyChoose.features = whyChoose.features.map(f => ({
          ...f,
          image: withBaseUrl(f.image),
        }));
      }

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

      return {
        ...t,
        banner,
        services_tabs_section_image: withBaseUrl(t.services_tabs_section_image),
        why_us_image,
        stand_out_section: stand_out_section_parse,
        why_choose_us_section: whyChoose,
        our_services_section: ourServices,
        service_section_Tabs: serviceTabs,
        all_services_grid: allServices,
        why_choose_us: whyChoose, // include for backward compatibility
      };
    });

    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 brandingAgencyTemplateModel.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 allServices = parseSafe(t.all_services_grid);
//     const whyChoose = parseSafe(t.why_choose_us_section);
//     const stand_out_section_parse = parseSafe(t.stand_out_section);

//     if (whyChoose?.features) {
//       whyChoose.features = whyChoose.features.map(f => ({
//         ...f,
//         image: withBaseUrl(f.image),
//       }));
//     }

   

//     const parsed = {
//       ...t,
//       banner,
//         services_tabs_section_image: withBaseUrl(t.services_tabs_section_image),
//         stand_out_section: stand_out_section_parse,
//         why_choose_us_section: parseSafe(t.why_choose_us_section),
//         our_services_section: parseSafe(t.our_services_section),
//         service_section_Tabs: serviceTabs,
//         all_services_grid: allServices,
//         why_choose_us: whyChoose,
//     };

//     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 });
//   }
// },



getTemplateById: async (req, res) => {
  try {
    const id = req.params.id;
    const template = await brandingAgencyTemplateModel.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 allServices = parseSafe(t.all_services_grid);
    const stand_out_section_parse = parseSafe(t.stand_out_section);

    const whyChoose = parseSafe(t.why_choose_us_section);
    if (whyChoose?.features) {
      whyChoose.features = whyChoose.features.map(f => ({
        ...f,
        image: withBaseUrl(f.image),
      }));
    }

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

      const get_reviews_url = `brand-agency-template/${id}`;
      const reviews = await reviews_faq_filterController.filterReviewsByRoute(get_reviews_url);

      const get_faqs = `brand-agency-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),
      stand_out_section: stand_out_section_parse,
      why_choose_us_section: whyChoose,
      our_services_section: ourServices,
      service_section_Tabs: serviceTabs,
      all_services_grid: allServices,
      why_choose_us: whyChoose,
      why_us_image: withBaseUrl(t.why_us_image),
      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 brandingAgencyTemplateModel.findByPk(id);
      if (!existing) {
        return res.status(404).json({ success: false, message: "Template not found" });
      }

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

      return res.status(200).json({
        success: true,
        message: "Branding Agency 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 brandingAgencyTemplateModel.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 = brandingAgencyTemplateController;
