import Category from '../models/category.model.js';
import slugify from "slugify";

// Create a new category (Admin only)
export const createCategory = async (req, res) => {
  try {
    const { name, projectId } = req.body;
    if (!projectId) return res.status(400).json({ message: "projectId is required" });

    const slug = slugify(name, { lower: true, strict: true });

    const category = await Category.create({
      name,
      slug,
      projectId
    });

    res.status(201).json(category);
  } catch (err) {
    res.status(500).json({ message: err.message });
  }
};

// Get all categories for a project
export const getCategories = async (req, res) => {
  try {
    const { projectId } = req.query;
    if (!projectId) return res.status(400).json({ message: "projectId is required" });

    const categories = await Category.find({ projectId }).sort({ name: 1 });
    res.json(categories);
  } catch (err) {
    res.status(500).json({ message: err.message });
  }
};

// Delete a category (Admin only)
export const deleteCategory = async (req, res) => {
  try {
    const { id } = req.params;
    await Category.findByIdAndDelete(id);
    res.json({ message: "Category deleted" });
  } catch (err) {
    res.status(500).json({ message: err.message });
  }
};
