const ServicesTab = require("../../models/home/servicesTabModel");

const ServicesTabController = {
  // Create one or multiple service tabs
  create: async (req, res) => {
    try {
      let input = req.body;

      // Ensure input is an array
      if (!Array.isArray(input)) input = [input];

      // Validate input
      const invalid = input.some(item =>
        !item.label ||
        !Array.isArray(item.content) ||
        item.content.length === 0
      );

      if (invalid) {
        return res.status(400).json({
          success: false,
          message: "Each item must include a non-empty label and a content array.",
        });
      }

      // Prepare data
      const serviceArray = input.map(item => ({
        service_label: item.label.trim(),
        service_content: item.content,
      }));

      // Check for bulkCreate support
      let createdServices;
      if (typeof ServicesTab.bulkCreate === 'function') {
        createdServices = await ServicesTab.bulkCreate(serviceArray);
      } else {
        // Fallback: create one by one
        createdServices = [];
        for (const data of serviceArray) {
          const record = await ServicesTab.create(data);
          createdServices.push(record);
        }
      }

      res.status(201).json({
        success: true,
        message: `${createdServices.length} service tab(s) created successfully!`,
        data: createdServices,
      });

    } catch (err) {
      res.status(500).json({ success: false, message: err.message });
    }
  },

  // Get all service tabs
  getAll: async (req, res) => {
    try {
      const result = await ServicesTab.findAll();
      if (!result.length) {
        return res.status(404).json({ success: false, message: "No service tabs found." });
      }
      res.status(200).json({ success: true, data: result });
    } catch (err) {
      res.status(500).json({ success: false, message: err.message });
    }
  },

  // Get a single service tab
  getSingle: async (req, res) => {
    try {
      const entry = await ServicesTab.findByPk(req.params.id);
      if (!entry) {
        return res.status(404).json({ success: false, message: "Service tab not found." });
      }
      res.status(200).json({ success: true, data: entry });
    } catch (err) {
      res.status(500).json({ success: false, message: err.message });
    }
  },

  // Update a service tab
 update: async (req, res) => {
  try {
    const updateData = Array.isArray(req.body) ? req.body[0] : req.body;
    const { label, content } = updateData;

    if (!label || !Array.isArray(content)) {
      return res.status(400).json({ success: false, message: "Label and content (array) are required." });
    }

    const data = {
      service_label: label.trim(),
      service_content: content,
    };

    const [updatedCount] = await ServicesTab.update(data, {
      where: { id: req.params.id },
    });

    if (!updatedCount) {
      return res.status(404).json({ success: false, message: "Service tab not found." });
    }

    const updatedRecord = await ServicesTab.findByPk(req.params.id);
    res.status(200).json({
      success: true,
      message: "Service tab updated successfully!",
      data: updatedRecord,
    });
  } catch (err) {
    res.status(500).json({ success: false, message: err.message });
  }
},


  // Delete a service tab
  delete: async (req, res) => {
    try {
      const deleted = await ServicesTab.destroy({ where: { id: req.params.id } });
      if (!deleted) {
        return res.status(404).json({ success: false, message: "Service tab not found." });
      }
      res.status(200).json({ success: true, message: "Service tab deleted successfully." });
    } catch (err) {
      res.status(500).json({ success: false, message: err.message });
    }
  },
};

module.exports = ServicesTabController;
