import { useQuery } from "@tanstack/react-query";
import { getCustomTagsSDK } from "services";
import { FanTag, FAN_TAG_COUNT_LIMIT } from "@komi-app/fans-sdk";
import { CustomTag as ReviewCustomTag } from "@komi-app/creator-ui/dist/src/screens/custom-tags/review-page/types";
import { camelToSnakeKeys } from "@komi-app/casing";

export function useCustomTagQuery() {
  return useQuery<{
    inactiveTagsWithCount: ReviewCustomTag[];
    totalTagCount: number;
  }>({
    refetchOnWindowFocus: false,
    queryKey: ["GetCustomTags"],
    queryFn: async () => {
      return await getAllFanTagsWithCount();
    },
  });
}

async function getAllFanTagsWithCount(): Promise<{
  inactiveTagsWithCount: ReviewCustomTag[];
  totalTagCount: number;
}> {
  //Get the ids of all inactive tags
  const tagsCollection: FanTag[] = await getCustomTagsSDK().getTags({});

  const inactiveTagIds = tagsCollection
    .filter((tag) => !tag.isActive)
    .map((tag) => tag.id);

  const tagAssociations =
    await getCustomTagsSDK().countTagAssociation(inactiveTagIds);

  // Map inactive tags to their counts
  const inactiveTagsWithCount: ReviewCustomTag[] = tagsCollection
    .filter((tag) => !tag.isActive)
    .map((tag) => {
      const tagWithCount = tagAssociations.find(
        (count) => count.id === tag.id,
      ) || { count: 0 };
      return camelToSnakeKeys({ ...tag, count: tagWithCount.count });
    })
    .filter((tag) => tag !== null);

  //Sort tags by count DESC
  inactiveTagsWithCount.sort(
    (a: ReviewCustomTag, b: ReviewCustomTag) => b.count - a.count,
  );

  return { inactiveTagsWithCount, totalTagCount: tagsCollection.length };
}
