import mongoose from "mongoose";
import { CategoryModel } from "./CategoryModel.js";

// Add new Category
export const addCategory = async (req, res) => {
  const { categoryName } = req.body;

  if (!req?.user) {
    return res.status(400).json({ message: "Please login!" });
  }

  try {
    if (!mongoose.Types.ObjectId.isValid(req.user._id)) {
      return res.status(400).json({ message: "Please login again." });
    }

    if (!categoryName) {
      return res.status(400).json({ message: "Please provide a category name" });
    }

    const category = await CategoryModel.create({
      categoryName,
      addedBy: req.user._id,
    });

    return res.status(201).json({ success: true, category, message: "Category added successfully" });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: error.message || "Something went wrong",
    });
  }
};

// Get all Categories
export const getCategories = async (req, res) => {
  try {
    const PAGE_SIZE = parseInt(req.query.show) || 10;
    const page = parseInt(req.query.page) || 1;
    const skip = (page - 1) * PAGE_SIZE;
    let filter = {};

    // Handle filtering by categoryName
    if (req.query.categoryName) {
      filter.categoryName = {
        $regex: new RegExp(req.query.categoryName, "i"),
      };
    }

    // Count the total number of documents matching the filter
    const total = await CategoryModel.countDocuments(filter);

    // Fetch the categories with pagination
    const categories = await CategoryModel.find(filter)
      .limit(PAGE_SIZE)
      .skip(skip)
      .sort({ createdAt: -1 })
      .exec();

    // If no categories are found, return a 404 error
    if (!categories.length) {
      return res.status(404).json({ message: "No categories found" });
    }

    // Return success response with total data and total pages
    res.status(200).json({
      success: true,
      total_data: total,
      total_pages: Math.ceil(total / PAGE_SIZE),
      current_page: page,
      categories,
    });
  } catch (error) {
    // Handle server error
    res.status(500).json({
      success: false,
      message: error.message || "Something went wrong",
    });
  }
};

// Update Category
export const updateCategory = async (req, res) => {
  const { _id } = req.params;
  const { categoryName } = req.body;

  if (!req?.user) {
    return res.status(400).json({ message: "Please login!" });
  }

  if (!mongoose.Types.ObjectId.isValid(_id)) {
    return res.status(404).json({ message: "Invalid category ID" });
  }

  try {
    const updatedCategory = await CategoryModel.findByIdAndUpdate(
      _id,
      { categoryName },
      { new: true, runValidators: true }
    );

    if (!updatedCategory) {
      return res.status(404).json({ message: "Category not found" });
    }

    res.status(200).json({ success: true, updatedCategory, message: "Category updated successfully" });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: error.message || "Something went wrong",
    });
  }
};

// Delete Category
export const deleteCategory = async (req, res) => {
  const { _id } = req.params;

  if (!req?.user) {
    return res.status(400).json({ message: "Please login!" });
  }

  if (!mongoose.Types.ObjectId.isValid(_id)) {
    return res.status(404).json({ message: "Invalid category ID" });
  }

  try {
    const deletedCategory = await CategoryModel.findByIdAndDelete(_id);

    if (!deletedCategory) {
      return res.status(404).json({ message: "Category not found" });
    }

    res.status(200).json({ success: true, deletedCategory, message: "Category deleted successfully" });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: error.message || "Something went wrong",
    });
  }
};
