const SubCategory = require("../../models/admin/subCategoryModel");
const { errorResponse } = require("../../utils/errorResponseHandler");
const { logUserAction } = require("../../utils/userActionLogger");

// Create SubCategory
const createSubCategory = async (req, res) => {
  try {
    const { subCategoryName, categoryId, orgId } = req.body;

    if (!subCategoryName)
      return errorResponse(res, "SubCategory name is required", 400);
    if (!categoryId)
      return errorResponse(res, "Category ID is required", 400);
    if (!orgId)
      return errorResponse(res, "Organization ID is required", 400);

    const userId = req.user?._id;

    // Check if subcategory with same name exists in the same category & org
    const existingSubCategory = await SubCategory.findOne({
      subCategoryName,
      categoryId,
      orgId,
    });

    if (existingSubCategory) {
      return errorResponse(
        res,
        "SubCategory name already exists in this category",
        409
      ); // 409 = Conflict
    }

    const subCategory = await SubCategory.create({
      subCategoryName,
      categoryId,
      orgId,
      createdBy: userId || null,
      updatedBy: null,
    });

    // Log user action
    await logUserAction({
      userId,
      orgId,
      action: "CREATE",
      model: "SubCategory",
      details: { subCategoryId: subCategory._id, subCategoryName },
      req,
    });

    res.status(201).json({ success: true, data: subCategory });
  } catch (error) {
    return errorResponse(res, "Failed to create SubCategory", 400, error);
  }
};


// Get All SubCategories with Pagination
const getSubCategories = async (req, res) => {
  try {
    let { page = 1, limit = 10 } = req.query;
    page = parseInt(page);
    limit = parseInt(limit);
    const skip = (page - 1) * limit;

    const query = { isDeleted: false };

    const [subCategories, total] = await Promise.all([
      SubCategory.find(query)
        .populate("createdBy", "firstName lastName email")
        .populate("updatedBy", "firstName lastName email")
        .populate("categoryId", "categoryName")
        .populate("orgId", "orgName")
        .skip(skip)
        .limit(limit)
        .sort({ createdAt: -1 }),
      SubCategory.countDocuments(query),
    ]);

    // Log user action
    await logUserAction({
      userId: req.user?._id,
      orgId: null,
      action: "READ",
      model: "SubCategory",
      details: { page, limit, count: subCategories.length },
      req,
    });

    res.status(200).json({
      success: true,
      total,
      page,
      pages: Math.ceil(total / limit),
      data: subCategories,
    });
  } catch (error) {
    return errorResponse(res, "Failed to fetch SubCategories", 500, error);
  }
};

// Get SubCategory by ID
const getSubCategoryById = async (req, res) => {
  try {
    const subCategory = await SubCategory.findById(req.params.id)
      .populate("createdBy", "firstName lastName email")
      .populate("updatedBy", "firstName lastName email")
      .populate("categoryId", "categoryName")
      .populate("orgId", "orgName");

    if (!subCategory) return errorResponse(res, "SubCategory not found", 404);

    // Log user action
    await logUserAction({
      userId: req.user?._id,
      orgId: subCategory.orgId,
      action: "READ",
      model: "SubCategory",
      details: { subCategoryId: subCategory._id },
      req,
    });

    res.status(200).json({ success: true, data: subCategory });
  } catch (error) {
    return errorResponse(res, "Error fetching SubCategory", 500, error);
  }
};

// Update SubCategory
// const updateSubCategory = async (req, res) => {
//   try {
//     const { status, subCategoryName, categoryId, orgId } = req.body;
//     const userId = req.user?._id;

//     const updateData = { updatedBy: userId || null, updatedAt: new Date() };
//     if (status !== undefined) updateData.status = status;
//     if (subCategoryName) updateData.subCategoryName = subCategoryName;
//     if (categoryId) updateData.categoryId = categoryId;
//     if (orgId) updateData.orgId = orgId;

//     const subCategory = await SubCategory.findByIdAndUpdate(
//       req.params.id,
//       updateData,
//       { new: true, runValidators: true }
//     )
//       .populate("createdBy", "firstName lastName email")
//       .populate("updatedBy", "firstName lastName email")
//       .populate("categoryId", "categoryName")
//       .populate("orgId", "orgName");

//     if (!subCategory) return errorResponse(res, "SubCategory not found", 404);

//     // Log user action
//     await logUserAction({
//       userId,
//       orgId: subCategory.orgId,
//       action: "UPDATE",
//       model: "SubCategory",
//       details: { subCategoryId: subCategory._id, updatedFields: updateData },
//       req,
//     });

//     res.status(200).json({ success: true, data: subCategory });
//   } catch (error) {
//     return errorResponse(res, "Failed to update SubCategory", 400, error);
//   }
// };
const updateSubCategory = async (req, res) => {
  try {
    const { status, subCategoryName, categoryId, orgId } = req.body;
    const userId = req.user?._id;

    // 🔴 DUPLICATE CHECK (exclude current record)
    if (subCategoryName && categoryId) {
      const duplicate = await SubCategory.findOne({
        _id: { $ne: req.params.id },   // exclude current subcategory
        subCategoryName: {
          $regex: `^${subCategoryName}$`,
          $options: "i",               // case-insensitive
        },
        categoryId,
        orgId,
        isDeleted: false,
      });

      if (duplicate) {
        return errorResponse(
          res,
          "SubCategory already exists under this category",
          409
        );
      }
    }

    // ✅ BUILD UPDATE DATA
    const updateData = {
      updatedBy: userId || null,
      updatedAt: new Date(),
    };

    if (status !== undefined) updateData.status = status;
    if (subCategoryName) updateData.subCategoryName = subCategoryName;
    if (categoryId) updateData.categoryId = categoryId;
    if (orgId) updateData.orgId = orgId;

    const subCategory = await SubCategory.findByIdAndUpdate(
      req.params.id,
      updateData,
      { new: true, runValidators: true }
    )
      .populate("createdBy", "firstName lastName email")
      .populate("updatedBy", "firstName lastName email")
      .populate("categoryId", "categoryName")
      .populate("orgId", "orgName");

    if (!subCategory) {
      return errorResponse(res, "SubCategory not found", 404);
    }

    await logUserAction({
      userId,
      orgId: subCategory.orgId,
      action: "UPDATE",
      model: "SubCategory",
      details: { subCategoryId: subCategory._id, updatedFields: updateData },
      req,
    });

    return res.status(200).json({ success: true, data: subCategory });
  } catch (error) {
    return errorResponse(res, "Failed to update SubCategory", 400, error);
  }
};


// Soft Delete SubCategory
const deleteSubCategory = async (req, res) => {
  try {
    const userId = req.user?._id;

    const subCategory = await SubCategory.findByIdAndUpdate(
      req.params.id,
      { isDeleted: true, updatedBy: userId || null },
      { new: true }
    );

    if (!subCategory) return errorResponse(res, "SubCategory not found", 404);

    // Log user action
    await logUserAction({
      userId,
      orgId: subCategory.orgId,
      action: "DELETE",
      model: "SubCategory",
      details: { subCategoryId: subCategory._id },
      req,
    });

    res.status(200).json({
      success: true,
      message: "SubCategory deleted successfully",
      data: subCategory,
    });
  } catch (error) {
    return errorResponse(res, "Failed to delete SubCategory", 500, error);
  }
};

// Get SubCategories by Category ID
const getSubCategoriesByCategoryId = async (req, res) => {
  try {
    const { categoryId } = req.params;
    if (!categoryId) return errorResponse(res, "Category ID is required", 400);

    const subCategories = await SubCategory.find({ categoryId, isDeleted: false })
      .populate("createdBy", "firstName lastName email")
      .populate("updatedBy", "firstName lastName email")
      .populate("categoryId", "categoryName")
      .populate("orgId", "orgName")
      .sort({ createdAt: -1 });

    // Log user action
    await logUserAction({
      userId: req.user?._id,
      orgId: null,
      action: "READ",
      model: "SubCategory",
      details: { categoryId, count: subCategories.length },
      req,
    });

    res.status(200).json({
      success: true,
      total: subCategories.length,
      data: subCategories,
    });
  } catch (error) {
    return errorResponse(res, "Failed to fetch subcategories by category", 500, error);
  }
};


module.exports = {
  createSubCategory,
  getSubCategories,
  getSubCategoriesByCategoryId,
  getSubCategoryById,
  updateSubCategory,
  deleteSubCategory,
};
