import slugifyPkg from "slugify";
import Category from "../models/categoryModel.js";

/**
 * Generate a slug for `name` and ensure uniqueness by checking DB.
 * If slug already exists, append -1, -2, ...
 */
export async function generateUniqueSlug(name) {
    const slugify = (s) => slugifyPkg(s, { lower: true, strict: true });
    let base = slugify(name || "");
    if (!base) base = `category-${Date.now()}`;

    let slug = base;
    let counter = 0;

    // Loop until a unique slug found
    // (should be fast; collisions are rare)
    // Note: use a simple findOne — acceptable here.
    while (true) {
        // findOne with exact slug
        const exists = await Category.findOne({ slug });
        if (!exists) return slug;

        counter += 1;
        slug = `${base}-${counter}`;
    }
}
