import { makeFetch } from "../../../../../../../../ChillMainBundle/Resources/public/lib/api/apiMethods";
import { Person } from "../../../../../../../../ChillPersonBundle/Resources/public/types";
import { ApiException } from "../../../../../../../../ChillMainBundle/Resources/public/types";
import { Module } from "vuex";
import { RootState } from "..";
import { Ticket } from ".././../../../types";
import { Thirdparty } from "src/Bundle/ChillThirdPartyBundle/Resources/public/types";

export interface State {
  persons: Person[];
}

export const modulePersons: Module<State, RootState> = {
  state: () => ({
    persons: [] as Person[],
  }),
  getters: {
    getPersons(state) {
      return state.persons;
    },
  },
  mutations: {
    setPersons(state, persons: Person[]) {
      state.persons = persons;
    },
  },
  actions: {
    async setPersons({ commit, rootState }, persons: Person[]) {
      const personData = persons.map((person: Person) => ({
        id: person.id,
        type: person.type,
      }));
      try {
        const result: Ticket = await makeFetch(
          "POST",
          `/api/1.0/ticket/${rootState.ticket.ticket.id}/persons/set`,
          { persons: personData },
        );
        commit("setTicket", result);

        return Promise.resolve();
      } catch (e: unknown) {
        const error = e as ApiException;
        throw error.name;
      }
    },
    async setCaller({ commit, rootState }, caller: Person | null) {
      try {
        const callerData = caller
          ? {
              id: caller.id,
              type: caller.type,
            }
          : null;
        const result: Ticket = await makeFetch(
          "POST",
          `/api/1.0/ticket/ticket/${rootState.ticket.ticket.id}/set-caller`,
          { caller: callerData },
        );
        commit("setTicket", result as Ticket);
      } catch (e: unknown) {
        const error = e as ApiException;
        throw error.name;
      }
    },

    async getSuggestedPersons({ commit, rootState }) {
      try {
        const ticketId = rootState.ticket.ticket.id;
        const caller = rootState.ticket.ticket.caller;
        const result: (Person | Thirdparty)[] = await makeFetch(
          "GET",
          `/api/1.0/ticket/ticket/${ticketId}/suggest-person`,
        );
        if (caller && !result.some((person) => person.id === caller.id)) {
          result.push(caller);
        }
        commit("setPersons", result);
      } catch (e: unknown) {
        const error = e as ApiException;
        throw error.name;
      }
    },
  },
};
