const { metaData } = require("../models/metaDataModel");

const MetaDataController = {
  create: async (req, res) => {
    try {
      const result = await metaData.create(req.body);
      if (result?.error) {
        return res.status(400).json({ success: false, message: result.error });
      }
      res.status(201).json({ success: true, data: result });
    } catch (err) {
      res.status(500).json({ success: false, message: err.message });
    }
  },

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

  getSingle: async (req, res) => {
    try {
      const record = await metaData.getSingle(req.params.id);
      if (!record) {
        return res.status(404).json({ success: false, message: "Meta record not found." });
      }
      res.status(200).json({ success: true, data: record });
    } catch (err) {
      res.status(500).json({ success: false, message: err.message });
    }
  },


  get_Single_page_by_slug: async (req, res) => {
    try {
      const record = await metaData.get_Single_page_by_slug(req.params.page_for);
      if (!record) {
        return res.status(404).json({ success: false, message: "Meta record not found." });
      }
      res.status(200).json({ success: true, data: record });
    } catch (err) {
      res.status(500).json({ success: false, message: err.message });
    }
  },

  update: async (req, res) => {
    try {
      const updated = await metaData.update(req.params.id, req.body);
      if (updated?.error) {
        return res.status(400).json({ success: false, message: updated.error });
      }
      if (!updated) {
        return res.status(404).json({ success: false, message: "Meta record not found." });
      }
      res.status(200).json({ success: true, message: "Meta updated!", data: updated });
    } catch (err) {
      res.status(500).json({ success: false, message: err.message });
    }
  },

  delete: async (req, res) => {
    try {
      const deleted = await metaData.delete(req.params.id);
      if (!deleted) {
        return res.status(404).json({ success: false, message: "Meta record not found." });
      }
      res.status(200).json({ success: true, ...deleted });
    } catch (err) {
      res.status(500).json({ success: false, message: err.message });
    }
  },
};

module.exports = MetaDataController;
