// models/userModel.js
const { DataTypes } = require("sequelize");
const sequelize = require("../../config/sequelize");
const { Op } = require("sequelize");

// Define category model
const categoryModel = sequelize.define(
  "category",
  {
    id: {
      type: DataTypes.INTEGER,
      primaryKey: true,
      autoIncrement: true,
    },
    name: {
      type: DataTypes.STRING,
      allowNull: false,
      unique:true
    },
    slug: {
      type: DataTypes.STRING(500), 
      allowNull: true,
      unique:true
    },
  },
  {
    timestamps: true,
    createdAt: "created_at",
    updatedAt: "updated_at",
    tableName: "Category",
  }
);

class category {
  // Create category
  static async create(CategoryData) {
  try {
    // Check for existing name
    if (CategoryData.name) {
      const nameExists = await categoryModel.findOne({
        where: { name: CategoryData.name.trim() },
      });

      if (nameExists) {
        return { error: "Category with this name already exists!" };
      }
    }

    // Check for existing slug
    if (CategoryData.slug) {
      const slugExists = await categoryModel.findOne({
        where: { slug: CategoryData.slug.trim() },
      });

      if (slugExists) {
        return { error: "Category slug already exists!" };
      }
    }

    // Create the category
    const newCategory = await categoryModel.create({
      name: CategoryData.name.trim(),
      slug: CategoryData.slug ? CategoryData.slug.trim() : "",
    });

    return {
      id: newCategory.id,
      name: newCategory.name,
      slug: newCategory.slug,
    };

  } catch (error) {
    throw error;
  }
}

  
  // Delete category
  static async deletecategory(id) {
    try {
      const category = await categoryModel.findByPk(id);
      if (!category) {
        return null;
      }

      await category.destroy();
      return { success: true, message: "category deleted successfully" };
    } catch (error) {
      throw error;
    }
  }

  // Get single category
  static async Get_Single_category(id) {
    try {
      const category = await categoryModel.findByPk(id); // better to use findByPk
      if(!category) {
        return null;
      }
      return category;
    } catch (error) {
      throw error;
    }
  }

  //get all category
  static async getcategory() {
    try {
      const category = await categoryModel.findAll();
      return category.length ? category : null;
    } catch (error) {
      throw error;
    }
  }


static async updatecategory(id, CategoryData) {
  try {
    const existingCategory = await categoryModel.findByPk(id);
    if (!existingCategory) return null;

    // Trim input
    if (CategoryData.name) CategoryData.name = CategoryData.name.trim();
    if (CategoryData.slug) CategoryData.slug = CategoryData.slug.trim();

    // ✅ Check for name uniqueness if name is changing
    if (CategoryData.name && CategoryData.name !== existingCategory.name) {
      const nameExists = await categoryModel.findOne({
        where: {
          name: CategoryData.name,
          id: { [Op.ne]: id },
        },
      });
      if (nameExists) {
        return { error: "Category name already exists." };
      }
    }

    // ✅ Check for slug uniqueness if slug is changing
    if (CategoryData.slug && CategoryData.slug !== existingCategory.slug) {
      const slugExists = await categoryModel.findOne({
        where: {
          slug: CategoryData.slug,
          id: { [Op.ne]: id },
        },
      });
      if (slugExists) {
        return { error: "Category slug already exists." };
      }
    }

    // ✅ Only update if something has changed
    const [updatedRows] = await categoryModel.update(CategoryData, {
      where: { id },
      individualHooks: true,
    });

    if (updatedRows === 0) return null;

    const updatedCategory = await categoryModel.findByPk(id);
    return updatedCategory;

  } catch (error) {
    throw error;
  }
}

  
}

module.exports = { category, categoryModel };
