type Data<T extends any = any> = Record<string, T>

export function fromSchemeRequest(data: Data) {
  return {
    children: data?.types?.map((item: Data) => {
      return {
        title: item?.type || '',
        children: item?.groups?.map((item: Data) => {
          return {
            ...fragment(item),
            descriptions: item?.attrs?.map(fragment) ?? [],
            media: fromSchemeMedia(item.items ?? []),
          };
        }) ?? [],
      };
    }) ?? [],
  };
}


function fragment(data: Data<string>) {
  return {
    title: data?.name || '',
    description: data?.description,
  };
}

export interface SchemeMediaProps {
  title: string;
  description: string;
  type: 'image' | 'video' | 'text';
  url: string;
  poster: string;
}

function fromSchemeMedia(data: Data[]) {
  const media: SchemeMediaProps[] = [];
  for ( const item of data ) {
    const type = item.mediaUrl ? 'video' : item.imgUrl ? 'image' : item.name ? 'text' : null;
    if ( !type ) continue;

    const title = item.type === 'medicine' ? [ item.name, `${ item.doase || '' }${ item.unit || '' }` ].filter(Boolean).join(' ') : item.name;
    media.push({
      type, title, description: item.description || '',
      url: item.mediaUrl ?? item.imgUrl, poster: item.imgUrl,
    });
  }
  return media;
}
