import { SYSTEM_TAGS_CATEGORY_OPTIONS } from '@/modules/editorial/TagEditor/constants';

import { iabFlatToTree } from '@/modules/@common/iab/helpers';

// custom tags
export function extractCustomTagsCategories(tags) {
  const categories = tags
    .reduce((acc, tag) => {
      const exist = acc.some((category) => category.label === tag.name);

      if (!exist) {
        acc.push({ id: tag.labelId, label: tag.name, color: tag.color });
      }

      return acc;
    }, [])
    .sort((cat, nextCat) => cat.label.localeCompare(nextCat.label));

  return categories;
}

export function normalizeCustomTags(categories, tags) {
  let result = [];

  categories.forEach((category) => {
    const orderedTagsBySystemTagValue = tags
      .filter((tag) => tag.name === category.label)
      .map((tag) => ({
        id: tag.labelId,
        label: tag.value,
        category: tag.name,
        color: category.color,
      }))
      .sort((tag, nextTag) => tag.label.localeCompare(nextTag.label));

    result = [].concat(result, orderedTagsBySystemTagValue);
  });

  return result;
}

// system tags
export function normalizeSystemTags(tags) {
  const clearTagLabel = (label) => label.trim().toLowerCase();
  let result = [];

  SYSTEM_TAGS_CATEGORY_OPTIONS.forEach((systemTag) => {
    const orderedTagsBySystemTagValue = tags
      .filter((tag) => tag.type.toUpperCase() === systemTag.value.replace('_', ''))
      .map((tag) => ({ id: tag.id, label: tag.text, category: tag.type.toUpperCase() }))
      .sort((tag, nextTag) => clearTagLabel(tag.label).localeCompare(clearTagLabel(nextTag.label)));

    result = [].concat(result, orderedTagsBySystemTagValue);
  });

  return result;
}

export const excludeCategoryBy = (excludeCategoryList, options) =>
  options.filter((option) => !excludeCategoryList.includes(option.value));

export const formatIabToTagEditorFormat = (iab) => ({
  data: JSON.stringify({
    categories: iabFlatToTree(iab),
  }),
});
