import { NextRequest, NextResponse } from "next/server";
import dbConnect from "@/lib/mongodb";
import Category from "@/models/Category";

export async function GET(req: NextRequest) {
  try {
    await dbConnect();

    // Get only parent categories
    const categories = await Category.find({
      parent: null,
      isActive: true,
    })
      .populate({
        path: "subcategories",
        match: { isActive: true },
        select: "_id name slug image level parent",
      })
      .sort({ name: 1 })
      .lean();

    return NextResponse.json({
      success: true,
      data: categories,
    });
  } catch (error: any) {
    console.error("Category Fetch Error:", error);

    return NextResponse.json(
      {
        success: false,
        message: error.message,
      },
      {
        status: 500,
      }
    );
  }
}