import { getCategories, getChildrenCategoryMultipleId } from "@/models/term";
import { response } from "@/utils/helper";

export async function GET(request) {
  try {
    const { searchParams } = new URL(request.url);
    const searchParamsData = Object.fromEntries(searchParams.entries());
    const queryRole = {
      page: parseInt(searchParamsData?.page) || 1,
      limit: parseInt(searchParamsData?.limit) || 100,
      sortBy: searchParamsData?.sortBy || "name",
      with: searchParamsData?.with || "desc",
      search: searchParamsData?.search || null,
    };
    const sortRole = {
      asc: 1,
      desc: -1,
    };

    const categories = await getCategories(
      {
        page: queryRole.page,
        limit: queryRole.limit,
      },
      { [queryRole.sortBy]: sortRole[queryRole.with] || -1 },
      queryRole.search
    );

    return response(200, "Get categories data successfully", categories);
  } catch (error) {
    console.log({ error });
    return response(500, "Internal Server Error", null, {
      error: "Failed to get categories data",
    });
  }
}

// Get children of category by id
export async function POST(request) {
  try {
    const body = await request.json();

    if (!body?.data || !Array.isArray(body?.data))
      return response(400, "Bad Request", null, {
        error: "Data type must be array",
      });

    const result = await getChildrenCategoryMultipleId(body.data);

    return response(200, "Get categories data successfully", result);
  } catch (error) {
    return response(500, "Internal Server Error", null, {
      error: "Failed to get categories data",
    });
  }
}
