const { parse } = require("dotenv");
const { VirtualEmployeesTemplate, VirtualEmployeesTemplateModel } = require("../../models/services_templates/VirtualEmployeesTemplateModel");
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 VirtualEmployeesTemplateController = {
  createTemplate: async (req, res) => {
    try {
      const newData = await VirtualEmployeesTemplateModel.create(req.body);
      return res.status(201).json({
        success: true,
        message: "Virtual Employees 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 VirtualEmployeesTemplateModel.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 standOut = parseSafe(t.stand_out_section);
        if (standOut?.background_file_url) {
          standOut.background_file_url = withBaseUrl(standOut.background_file_url);
        }

        if (standOut?.image) {
          standOut.image = withBaseUrl(standOut.image);
        }


        const ourAchievements = parseSafe(t.our_achievements_section);

        const challenges = parseSafe(t.challenges_section);
        if (challenges?.sections_cards) {
          challenges.sections_cards = challenges.sections_cards.map(c => ({
            ...c,
            icon_url: withBaseUrl(c.icon_url),
          }));
        }

        const ourExperties = parseSafe(t.our_experties_section);
        if (ourExperties?.experties_cards) {
          ourExperties.experties_cards = ourExperties.experties_cards.map(c => ({
            ...c,
            icon_url: withBaseUrl(c.icon_url),
          }));
        }

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

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

        const aboutUs = parseSafe(t.about_us_section);
        if (aboutUs?.background_file_url) {
          aboutUs.background_file_url = withBaseUrl(aboutUs.background_file_url);
        }
        if (aboutUs?.left_hand_file) {
          aboutUs.left_hand_file = withBaseUrl(aboutUs.left_hand_file);
        }

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

        return {
          ...t,
          banner,
          stand_out_section: standOut,
          our_achievements_section: ourAchievements,
          challenges_section: challenges,
          our_experties_section: ourExperties,
          information_card: infoCard,
          our_top_clients_section: topClients,
          about_us_section: aboutUs,
          portfolio_section: portfolio,
        };
      });

      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 VirtualEmployeesTemplateModel.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 standOut = parseSafe(t.stand_out_section);
      if (standOut?.background_file_url) {
        standOut.background_file_url = withBaseUrl(standOut.background_file_url);
      }
      if (standOut?.image) {
        standOut.image = withBaseUrl(standOut.image);
      }
      const ourAchievements = parseSafe(t.our_achievements_section);

      const challenges = parseSafe(t.challenges_section);
      if (challenges?.sections_cards) {
        challenges.sections_cards = challenges.sections_cards.map(c => ({
          ...c,
          icon_url: withBaseUrl(c.icon_url),
        }));
      }

      const ourExperties = parseSafe(t.our_experties_section);
      if (ourExperties?.experties_cards) {
        ourExperties.experties_cards = ourExperties.experties_cards.map(c => ({
          ...c,
          icon_url: withBaseUrl(c.icon_url),
        }));
      }

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

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

      const aboutUs = parseSafe(t.about_us_section);
      if (aboutUs?.background_file_url) {
        aboutUs.background_file_url = withBaseUrl(aboutUs.background_file_url);
      }
      if (aboutUs?.left_hand_file) {
        aboutUs.left_hand_file = withBaseUrl(aboutUs.left_hand_file);
      }

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

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

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

      const parsed = {
        ...t,
        banner,
        stand_out_section: standOut,
        our_achievements_section: ourAchievements,
        challenges_section: challenges,
        our_experties_section: ourExperties,
        information_card: infoCard,
        our_top_clients_section: topClients,
        about_us_section: aboutUs,
        portfolio_section: portfolio,
        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 VirtualEmployeesTemplateModel.findByPk(id);
      if (!existing) {
        return res.status(404).json({ success: false, message: "Template not found" });
      }

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

      return res.status(200).json({
        success: true,
        message: "Virtual Employees 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 VirtualEmployeesTemplateModel.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 = VirtualEmployeesTemplateController;
