import { ExtendedPerson } from '@interfaces/services/personal-accounts';
import {
  DocumentTypesApi,
  DocumentType,
  ContactData,
  PersonAddress,
  PersonDocument,
} from '@openapi/personal-accounts';
import { get, isEmpty, isNil, set } from 'lodash';
import { GetterTree, MutationTree, ActionTree } from 'vuex';

interface DocumentTypeIndex {
  [documentType: string]: {
    [name: string]: string | undefined;
  };
}
type Exrensions = Pick<
  ExtendedPerson,
  'personaddress' | 'contactdata' | 'persondocument'
>;
const documentLinks: Record<string, keyof Exrensions> = {
  address: 'personaddress',
  contact: 'contactdata',
  dul: 'persondocument',
};
const documentTypeKeys: Record<string, string> = {
  address: 'addressType',
  contact: 'contactType',
  dul: 'documentType',
};

export const state = {
  types: [] as DocumentType[],
  typesIndex: {} as DocumentTypeIndex,
};

export type State = typeof state;

export const getters: GetterTree<State, State> = {
  applyDictionaris(state): (model: ExtendedPerson) => ExtendedPerson {
    return (model) => {
      return Object.keys(documentLinks).reduce(
        (data, documentType) => {
          data[documentLinks[documentType]]?.forEach(
            (d: ContactData | PersonAddress | PersonDocument) => {
              const typeKey = documentTypeKeys[documentType];
              const type = get(d, typeKey) as string;

              set(d, typeKey, state.typesIndex[documentType][type]);
            }
          );
          return data;
        },
        { ...model }
      );
    };
  },
};

export const mutations: MutationTree<State> = {
  setDictionary(state, documentTypes: DocumentType[]) {
    state.types = documentTypes;
  },
  setIndex(state, documentTypes: DocumentType[]) {
    state.typesIndex = documentTypes.reduce(
      (index, { documentType, name, description }) => {
        if (isNil(documentType) || isNil(name)) return index;
        if (isEmpty(index[documentType])) index[documentType] = {};
        index[documentType][name] = description;
        return index;
      },
      {} as DocumentTypeIndex
    );
  },
};

export const actions: ActionTree<State, State> = {
  async initDictionary({ commit }): Promise<DocumentType[] | void> {
    try {
      const documentTypesApi = new DocumentTypesApi();
      const { data } = await documentTypesApi.listDocumentTypes();
      commit('setDictionary', data);
      commit('setIndex', data);
      return data;
    } catch (error) {
      console.warn(`[perconal-accounts] Couldn't get types of documents`);
    }
  },
};
