import * as _ from 'lodash'
import {ApiResponse, DataProviderArgs, Processor} from '~/types/interfaces'
import BaseProcessor from '~/services/data/processor/baseProcessor'
import {METADATA_TYPE, QUERY_TYPE} from '~/types/enums'
import { repositoryHelper } from '~/services/store/repository'

class ModelProcessor extends BaseProcessor implements Processor {
  /**
   * Is the given argument a supported model
   * @param args
   */
  public static support (args: DataProviderArgs): boolean {
    return args.type === QUERY_TYPE.MODEL
  }

  /**
   * Exécute la requête et retourne la réponse désérialisée
   * @param data
   */
  async process (payload: ApiResponse): Promise<any> {
    if (typeof this.arguments.model === 'undefined') {
      throw new TypeError('model must be defined')
    }

    if(payload.metadata.type !== METADATA_TYPE.COLLECTION){
      payload.data.originalState = _.cloneDeep(payload)
    }
    await repositoryHelper.persist(this.arguments.model, payload.data)

    return payload
  }
}

export default ModelProcessor
