import { createTags, getTagsBySlugs } from "@/models/term";
import { response } from "@/utils/helper";

export async function POST(request) {
  try {
    const body = await request.json();

    if (!body?.data)
      return response(400, "Bad Request", null, { error: "Data is required" });

    // find slug is already or not
    const slugs = body.data.map((item) => item.slug);
    const tagsExist = await getTagsBySlugs(slugs);

    let unavailableTags = body.data;
    if (tagsExist.length > 0)
      unavailableTags = body.data.filter(
        (item) => !tagsExist.map((tag) => tag.slug).includes(item.slug)
      );

    // insert new tags
    let result = [];
    if (unavailableTags.length > 0) result = await createTags(unavailableTags);

    const mergeResult = [...tagsExist, ...result];
    return response(200, "Add tag successfully", mergeResult);
  } catch (error) {
    console.log(error);
    return response(500, "Internal Server Error", null, {
      error: "Failed to add tag",
    });
  }
}
