import { fetchClient } from '../../../lib/fetch-client';
import BLOCK_DEFINITIONS from '../config/blocks';
import createBlockMenu, { type RawBlockMenu } from '../utils/createBlockMenu';
import type {
  CustomClassItem,
  ImageSizesItem,
  FontSizeItem,
  FontFamilyItem,
  FeaturesSetting,
  EditorSettings,
} from '../types/index';

interface RawSettingsResponse {
  features?: FeaturesSetting;
  blockMenus?: RawBlockMenu;
  fontSize?: FontSizeItem[];
  fontFamily?: FontFamilyItem[];
  customClass?: CustomClassItem[];
  imageSizes?: ImageSizesItem[];
  colorPalette?: string[];
}

const defaultFeatures: FeaturesSetting = {
  textItalic: false,
  textUnderline: false,
  textStrike: false,
  textCode: false,
  textMarker: false,
  textColor: false,
  fontSize: false,
  fontFamily: false,
  textSubscript: false,
  textSuperscript: false,
  customClass: false,
  tableBgColor: false,
  imageDefaultLightbox: true,
};

const fetchSettings = async (): Promise<EditorSettings> => {
  const endpoint = ACMS.Library.acmsLink(
    {
      tpl: 'ajax/edit/block-editor/settings.json',
      bid: ACMS.Config.bid,
      cid: ACMS.Config.cid,
    },
    false
  );
  const { data } = await fetchClient.get<RawSettingsResponse>(endpoint);
  const raw: RawSettingsResponse = data ?? {};
  return {
    features: raw.features ?? defaultFeatures,
    blockMenus: createBlockMenu(raw.blockMenus ?? [], BLOCK_DEFINITIONS),
    fontSize: raw.fontSize ?? [],
    fontFamily: raw.fontFamily ?? [],
    customClass: raw.customClass ?? [],
    imageSizes: raw.imageSizes ?? [],
    colorPalette: raw.colorPalette ?? [],
  };
};

export { fetchSettings };
