const Category = require("../../models/admin/categoryModel");
const { errorResponse } = require("../../utils/errorResponseHandler");
const { logUserAction } = require("../../utils/userActionLogger");
const  getRelativePath  = require("../../utils/getRelativePath");

// Create Category
const createCategory = async (req, res) => {
  try {
    const { categoryName, orgId } = req.body;

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

    // Check if image is uploaded
    if (!req.file) return errorResponse(res, "Category image is required", 400);

    const userId = req.user?._id;

    // Check if category with same name exists in the org
    const existingCategory = await Category.findOne({ categoryName, orgId });
    if (existingCategory) {
      return errorResponse(res, "Category name already exists in this organization", 409);
    }

    const category = await Category.create({
      categoryName,
      orgId,
      image: getRelativePath(req.file.path),
      createdBy: userId || null,
      updatedBy: null,
    });

    const populatedCategory = await Category.findById(category._id)
  .populate("createdBy", "firstName lastName")
  .populate("updatedBy", "firstName lastName");

    // Log user action
    await logUserAction({
      userId,
      orgId,
      action: "CREATE",
      model: "Category",
      details: { categoryId: category._id, categoryName },
      req,
    });

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



// Get All Categories with Pagination (exclude soft deleted)
const getCategories = 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 [categories, total] = await Promise.all([
      Category.find(query)
        .populate("createdBy", "firstName lastName email")
        .populate("updatedBy", "firstName lastName email")
        .populate("orgId", "orgName")
        .skip(skip)
        .limit(limit)
        .sort({ createdAt: -1 }),
      Category.countDocuments(query),
    ]);

    // Log user action
    await logUserAction({
      userId: req.user?._id,
      // userId : req.user.id,
      orgId: req.user?.orgId || null, // assume orgId from logged-in user if not filtering by query
      action: "READ",
      model: "Category",
      details: { page, limit, count: categories.length },
      req,
    });

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

// Get Category by ID
const getCategoryById = async (req, res) => {
  try {
    const category = await Category.findById(req.params.id)
      .populate("createdBy", "firstName lastName email")
      .populate("updatedBy", "firstName lastName email")
      .populate("orgId", "orgName");

    if (!category) return errorResponse(res, "Category not found", 404);

    // Log user action
    await logUserAction({
      // userId: req.user?._id,
      userId : req.user.id,
      orgId: category.orgId?._id || null,
      action: "READ",
      model: "Category",
      details: { categoryId: category._id },
      req,
    });

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

// Update Category
// const updateCategory = async (req, res) => {
//   try {
//     const { status, categoryName, orgId } = req.body;
//     const userId = req.user?._id;

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

//      if (req.file) {
//       updateData.image = `/uploads/images/${req.file.filename}`;
//     }

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

//     if (!category) return errorResponse(res, "Category not found", 404);

//     // Log user action
//     await logUserAction({
//       userId,
//       orgId: category.orgId?._id || orgId || null,
//       action: "UPDATE",
//       model: "Category",
//       details: { categoryId: category._id, updatedFields: updateData },
//       req,
//     });

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

    //  DUPLICATE CHECK (exclude current category)
    if (categoryName) {
      const duplicate = await Category.findOne({
        _id: { $ne: req.params.id }, // exclude current category
        categoryName: {
          $regex: `^${categoryName}$`,
          $options: "i", // case-insensitive
        },
        orgId,
        isDeleted: false,
      });

      if (duplicate) {
        return errorResponse(
          res,
          "Category already exists in this organization",
          409
        );
      }
    }

    const updateData = {
      updatedBy: userId || null,
      updatedAt: new Date(),
    };

    if (status !== undefined) updateData.status = status;
    if (categoryName) updateData.categoryName = categoryName;
    if (orgId) updateData.orgId = orgId;

    if (req.file) {
      updateData.image = `/uploads/images/${req.file.filename}`;
    }

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

    if (!category) return errorResponse(res, "Category not found", 404);

    await logUserAction({
      userId,
      orgId: category.orgId?._id || orgId || null,
      action: "UPDATE",
      model: "Category",
      details: { categoryId: category._id, updatedFields: updateData },
      req,
    });

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


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

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

    if (!category) return errorResponse(res, "Category not found", 404);

    // Log user action
    await logUserAction({
      userId,
      orgId: category.orgId?._id || null,
      action: "DELETE",
      model: "Category",
      details: { categoryId: category._id },
      req,
    });

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

module.exports = {
  createCategory,
  getCategories,
  getCategoryById,
  updateCategory,
  deleteCategory,
};
