import {recursiveFieldDecorator} from './ObjectUtils';

export interface Attribute {
  name: string;
  type: string;
  value: any;
}

interface AttributeArray extends Array<Attribute> {
  byName?: Record<string, any>;
}

export const decorateQueryResult = <T>(result: T): T => {
  if (!result) return result;
  return recursiveFieldDecorator(result, (target: any, key: any) => {

    const value = target[key];
    if (value) {
      if (key === 'attributes' && Array.isArray(value)) {
        const attrCopy: AttributeArray = [...value];
        attrCopy['byName'] = value.reduce((acc: Record<string, any>, attr: Attribute) => {
          const name = (attr.name || '').replace(/[^a-z0-9_]/ig, '');
          acc[name] = attr.value;
          return acc;
        }, {});
        return attrCopy;
      }
    }
    return value;
  });
};