// @ts-nocheck
import { Request, Response } from "express";
import asyncHandler from "../utils/asyncHandler";
import ApiError from "../utils/apiError";
import ApiResponse from "../utils/apiResponse";
import prisma from "../DB/db";
import slugify from "slugify";

// --- Get Category Tree (Public) ---
export const getCategoryTree = asyncHandler(async (req, res) => {
  const categories = await prisma.category.findMany({
    where: { parentId: null },
    include: {
      children: {
        include: {
          children: true, // supports deep nesting
        },
      },
    },
    orderBy: { name: "asc" },
  });

  res.json(new ApiResponse(true, 200, "Category tree", categories));
});


// --- Create Category (Admin) ---
export const createCategory = asyncHandler(async (req: Request, res: Response) => {
  const { name, parentId, description, image } = req.body;

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

  const category = await prisma.category.create({
    data: {
      name,
      slug,
      parentId: parentId || null, // Optional parent
      description,
      image
    },
  });

  return res.status(201).json(new ApiResponse(true, 201, "Category created", category));
});