import { IGenericHeader } from '../../../generic/types';
import { ISlackHeader, ISlackSection } from '../../types';
import { getMethods } from '../methods';

function transformHeader({ props, children }: IGenericHeader): ISlackHeader|ISlackSection {
  const block_id = props?.slack?.block_id;

  const text = children
    .reduce((acc, item) => {
      const elem = getMethods(item.type)(item);
      if (elem.type !== 'plain_text' && elem.type !== 'mrkdwn') return acc;

      if (!acc.type) return elem;
      return acc.text += ` ${elem.text}`;
    }, {});

  const res: ISlackHeader|ISlackSection = {
    type: text.type === 'plain_text' ? 'header' : 'section', // header section doesn't support mrkdwn text
    text: text.type === 'plain_text' ? text : Object.assign(text, { text: `*${text.text}*`})
  };

  if (block_id) res.block_id = block_id;

  return res;
}

export {
  transformHeader
};
