const { DataTypes, Op } = require("sequelize");
const sequelize = require("../config/sequelize");

const metaDataModel = sequelize.define(
  "meta_data",
  {
    meta_title: { type: DataTypes.STRING, allowNull: true },
    meta_description: { type: DataTypes.STRING, allowNull: true },
    meta_keywords: { type: DataTypes.JSON, allowNull: true }, 
    slug: { type: DataTypes.STRING, allowNull: false, unique: true },
    canonical_tag: { type: DataTypes.STRING, allowNull: true },
    og_url: { type: DataTypes.STRING, allowNull: true },
    og_sitename: { type: DataTypes.STRING, allowNull: true },
    page_for: {
      type: DataTypes.ENUM("home_page", "blogs_page", "services_page"),
      allowNull: false,
    },
  },
  {
    tableName: "meta_data",
    underscored: true,
  }
);

const metaData = {
  create: async (data) => {
    try {
      if (!data.slug || !data.page_for)
        return { error: "Slug and page_for are required." };

      const exists = await metaDataModel.findOne({
        where: { slug: data.slug },
      });
      if (exists) return { error: "Slug already exists." };

      const newMeta = await metaDataModel.create(data);
      return newMeta;
    } catch (err) {
      throw err;
    }
  },

  getAll: async () => {
    try {
      return await metaDataModel.findAll({ order: [["created_at", "DESC"]] });
    } catch (err) {
      throw err;
    }
  },

  getSingle: async (id) => {
    try {
      return await metaDataModel.findByPk(id);
    } catch (err) {
      throw err;
    }
  },

  get_Single_page_by_slug: async (page_for) => {
    try {
      return await metaDataModel.findOne({
        where:{page_for,page_for}
      });
    } catch (err) {
      throw err;
    }
  },

  update: async (id, data) => {
    try {
      const record = await metaDataModel.findByPk(id);
      if (!record) return null;

      // Check slug uniqueness
      if (data.slug && data.slug !== record.slug) {
        const dup = await metaDataModel.findOne({
          where: { slug: data.slug, id: { [sequelize.Op.ne]: id } },
        });
        if (dup) return { error: "Slug already exists." };
      }

      await metaDataModel.update(data, { where: { id } });
      return await metaDataModel.findByPk(id);
    } catch (err) {
      throw err;
    }
  },

  delete: async (id) => {
    try {
      const deleted = await metaDataModel.destroy({ where: { id } });
      if (!deleted) return null;
      return { message: "Meta data deleted successfully!" };
    } catch (err) {
      throw err;
    }
  },
};

module.exports = { metaDataModel, metaData };
