import { getTagsPagination } 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 tags = await getTagsPagination(
      {
        page: queryRole.page,
        limit: queryRole.limit,
      },
      { [queryRole.sortBy]: sortRole[queryRole.with] || -1 },
      queryRole.search
    );

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

export async function POST(request) {
  try {
    const body = await request.json();
    const tags = await getTagsPagination(
      { page: 1, limit: 100 },
      { name: 1 },
      body.data,
      true
    );

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