import {
  fetchResults,
  makeFetch,
} from "../../../../../../../../ChillMainBundle/Resources/public/lib/api/apiMethods";

import { Module } from "vuex";
import { RootState } from "..";

import { Motive } from "../../../../types";
import { ApiException } from "../../../../../../../../ChillMainBundle/Resources/public/types";

export interface State {
  motives: Motive[];
}

export const moduleMotive: Module<State, RootState> = {
  state: () => ({
    motives: [] as Motive[],
  }),
  getters: {
    getMotives(state) {
      return state.motives;
    },
    getMotiveById: (state) => (motiveId: number) => {
      const findInChildren = (motives: Motive[]): Motive | null => {
        for (const motive of motives) {
          if (motive.id === motiveId) return motive;
          const found = motive.children?.length
            ? findInChildren(motive.children)
            : null;
          if (found) return found;
        }
        return null;
      };
      return findInChildren(state.motives);
    },
  },
  mutations: {
    setMotives(state, motives) {
      state.motives = motives;
    },
  },
  actions: {
    async fetchMotives({ commit }) {
      try {
        const results = (await fetchResults(
          "/api/1.0/ticket/motive.json",
        )) as Motive[];
        commit("setMotives", results);
      } catch (e: unknown) {
        const error = e as ApiException;
        throw error.name;
      }
    },

    async createMotive({ commit, rootState }, motive: Motive) {
      try {
        const result = await makeFetch(
          "POST",
          `/api/1.0/ticket/${rootState.ticket.ticket.id}/motive/set`,
          {
            motive: {
              id: motive.id,
              type: motive.type,
            },
          },
        );
        commit("setTicket", result);
      } catch (e: unknown) {
        const error = e as ApiException;
        throw error.name;
      }
    },
  },
};
