import { Form, FormApi } from '@openapi/registry-service';
import { ActionTree, GetterTree, MutationTree } from 'vuex';
const formApi = new FormApi();

export const state = {
  schemes: {} as Index,
};

type Index = {
  [key: string]: Form;
};

export type State = typeof state;

export const getters: GetterTree<State, State> = {
  getFromIndex(state): (formID: string) => Form | undefined {
    return (formID) => state.schemes[formID];
  },
};

export const mutations: MutationTree<State> = {
  index(state, { formID, schema }: { formID: string; schema: Form }): void {
    state.schemes[formID] = schema;
  },
};

export const actions: ActionTree<State, State> = {
  async fetchSchemaByCode({ commit, getters }, formID) {
    try {
      let form = getters.getFromIndex(formID);
      if (!form) {
        const responce = await formApi.getForm(formID);
        form = responce.data;
        commit('index', form);
      }
      return form;
    } catch (error) {
      console.warn(`Couldn't get schema ${formID}`);
    }
  },
};
